JavaScript之this引用

在javascript的函数中,除了函数声明时定义的形参之外,每个函数还可以接收另一个隐藏的参数:this,又称this引用。

this的作用及在不同场景下的不同指向

this的值(即它的指向)取决于调用的方式。在javascript中this指向大致有四种情况:
1.无任何前缀的函数调用时,this指向顶层对象或者叫全局对象,浏览器里是window(nodejs里是global)。

function hello(){
          console.log(this);
}
hello();        //打印结果为window{...}

2.方法调用
当一个函数被保存为对象的一个属性时,我们称它为一个方法。当一个方法被调用时,this被绑定到该对象

var hello = {
            name:"sunshine",
            age:18,
            say:function(){
                   console.log(this.name)
                }
            };
hello.say();        //打印结果为'sunshine'

3.构造函数里,this指向新生成的实例

function Hello(name){
    this.name = name;
    this.age = 18,
    this.say = function(){
                console.log(this.name)
             }
}
var robot_1 = new Robot('tom');
robot_1.say()        //  打印结果为'tom'
var robot_2 = new Robot('mary');
robot_2.say()        //  打印结果为'mary'

4.apply/call调用的时候,this指向apply/call方法中的第一个参数

var hello_1 = {name:'mary'}
var hello_2 = {name:'tom'}

function say(){
  console.log(this.name)
}
say.call(hello_1)     //  打印结果为'mary'
say.apply(hello_2)     //  打印结果为'tom'

5.函数调用模式
如果一个函数并非一个对象的属性时,那么它被当作一个函数来调用,此时,this被绑定到全局对象。

var myObject = {
  value:1,
  getValue:function(){
    console.log(this.value)
  },
  double:function(){
    return function(){
      console.log(this.value = this.value * 2); 
    }
  }
}

myObject.double()();  //希望value乘以2
myObject.getValue();  //1

因为 ,我们希望调用 myObject.double()() 时,value 乘以 2,但是由于 myObject.double() 返回的是一个函数,而 myObject.double()() 执行了返回的这个函数,此时,this被绑定到了全局 window 而不是 myObject。
解决方法:

var myObject = {
  value:1,
  getValue:function(){
    console.log(this.value)
  },
  double:function(){
    var that = this;
    return function(){
      console.log(that.value = that.value * 2); 
    }
  }
}

myObject.double()();  //2
myObject.getValue();  //2

即是给该方法定义一个变量并且把它赋值为this,那么内部函数就可以通过那个变量访问到this,按照约定,给那个变量命名为that。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容