JavaScript中的this

2016-10-07  本文已影响11人  不知所语

JavaScript中的this

以下内容属于个人的归纳总结(请大神们多多指点!!!)
随着函数的使用场合不同,this的值会发生变化(this代表函数运行时自动生成的一个内部对象)

全局执行

console.log(this);//浏览器:Window //node:{}

函数中执行

纯粹的函数调用

function hello(){ 
  console.log(this);
}
hello();//Window global

可以看到函数直接调用时,属于全局调用,this指全局对象

严格模式

'use strict';
function hello(){
  console.log(this);
}
hello();//undefined

可以看到在严格模式下执行纯粹的函数调用,this指向的是undefined

作为对象的方法调用

当一个函数被当作对象的方法调用时,this指当前这个对象

var o = { 
  x: 7, 
  test: function(){ 
    console.log(this.x); 
}};
o.test(); //this指o这个对象

在setTimeout中使用

var o = {
  name: 'Jony',
  f1: function(){ 
    console.log(this); //全局对象 
},
  f2: function(){
    console.log(this); //o这个对象
    setTimeout(this.f1, 1000);
  }
};
o.f2();

在setTimeout这里要注意的是:**把this.f1当作参数传进来,这里的参数指向的是this.f1的引用,只是被当作普通函数的直接调用,所以这里的this跟o没有关系,指全局对象。
**大家可以思考下面这个例子的打印结果是什么???

'use strict';
function test() { 
  console.log(this);
}
setTimeout(test, 1000);

上面我提到了在严格模式下this是undefined,但是在setTimeout中this如果没有指定,相当于test.apply(global);

作为构造函数调用

var x = 9;
function test() {
  this.x = 8; //this指的构造函数调用时实例化出来的对象
}
var a = new test();
console.log(a.x); //8
console.log(x); //9

箭头函数

在这里我想说一下箭头函数的好处之一 :可以改变this的指向请看下面两段代码:

var o = { 
  name: 'Jony',
  f1: function(){ 
    console.log(this); 
  },
  f2: function(){ 
    console.log(this); //o这个对象 
    var _this = this; 
    setTimeout(function(){ 
      console.log(this); //全局对象 
      console.log(_this); //o这个对象 
    }, 1000); 
  }
};
o.f2();

问题:setTimeout中的this是全局对象因此我们采用闭包的特性——把this存储在内存中,使用这种方式解决上面的问题但是在箭头函数中我们可以更方便的解决this的指向问题,请看下面:

var o = { 
  name: 'Jony',
  f1: function(){ 
    console.log(this); 
  }, 
  f2: function(){ 
    console.log(this); //o这个对象 
    setTimeout(() => { 
      console.log(this); //o这个对象 
    }, 1000); 
  }
};
o.f2();//箭头函数中的this只跟定义它时作用域中的this有关

以上是我对JS中的this浅显的理解,仅供参考!

上一篇 下一篇

猜你喜欢

热点阅读