zoukankan      html  css  js  c++  java
  • js中this的用法

    在函数内部有两个特殊对象:arguments和this,this的指向其实是非常灵活的,它会根据调用function的对象不同,导致了this的指向不同。当在全局作用域下调用函数时,this指向window。例如:

    window.color = 'red';
    var o = {color: 'blue'};
    function sayColor(){
       alert(this.color);
    }
    sayColor(); //'red'
    o.sayColor = sayColor;
    o.sayColor(); //'blue'
    

      我们知道this对象在执行时是基于函数的执行环境绑定的:当函数被作为某个对象的方法调用时,this指向那个对象。但匿名函数的执行环境具有全局性,所以this指向window。但在闭包中,这一点可能不太明显。先说一下闭包吧,我的理解是在一个函数内部创建另一个函数,而内部函数可以访问外部函数作用域中的变量,这是因为内部函数的作用域链中包含外部函数的作用域。

    var name = 'the window';
    var object = {
      name: 'My object',
      getFunc: function (){
         return function(){
            return this.name;
         }
      }
    };
    alert(object.getFunc()());   //'the window'

        看到这里,大家可能会惊讶,为什么this指向的是全局作用域。因为内部函数在搜索this和arguments时,只会搜索到其活动对象,永远不可能直接访问外部函数中的这两个变量。

    为了让闭包内的this能访问到外部作用域中的变量,我们可以在定义匿名函数之前把this附一个值,当定义闭包后就可以访问外部变量了。因为它是我们在外部函数(包含函数)中特意声明的一个变量。

    var name = 'the window';
    var object = {
      name: 'My object',
      getFunc: function (){
         var that = this;
         return function(){
            return that.name;
         }
      }
    };
    alert(object.getFunc()());   //'My object'
    

      

  • 相关阅读:
    LeetCode Flatten Binary Tree to Linked List
    LeetCode Longest Common Prefix
    LeetCode Trapping Rain Water
    LeetCode Add Binary
    LeetCode Subsets
    LeetCode Palindrome Number
    LeetCode Count and Say
    LeetCode Valid Parentheses
    LeetCode Length of Last Word
    LeetCode Minimum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/ssh-007/p/4933313.html
Copyright © 2011-2022 走看看