js中this指向

在开发和面试中总是遇到this,每次看过之后过几天都会忘记。于是下定决心彻底弄懂this指向问题。

1.在函数内部和全局中使用,this总是指向全局,在浏览器中是window,node中为global。

var a = 'this window';
console.log(this.a);
function m () {
  console.log(this.a);      
}
m();// this window

2.在函数调用时,函数内部this指向其调用环境。

function func() {
  console.log(this);      
}
var obj = {
  func  
}
obj.func();// 指向obj

3.在构造函数和构造函数的原型对象中,this指向实例。

function A(name) {
  this.name = 'name';            
  this._this = this;
  console.log(this);
}
var a = new A();

4.匿名函数中this。由于匿名函数执行具有全局性,因此匿名函数的this指向window。

5.箭头函数不绑定this,取决于其定义的上下文。

6.setTimeout和setInterval,内部的回调函数指向全局。

7.通过apply,call以及bind可以改变this的指向。

posted @ 2018-10-18 17:39  Pomm  阅读(219)  评论(0编辑  收藏  举报