this的指向有哪些
函数的调用方式决定了this的值(运行时绑定),this不能再执行期间被赋值,并且在每次函数调用时this的值夜可能会不同。
共有7种。
全局上下文
this:全局对象
this === window
函数上下文
this的指向取决于函数被调用的方式。
- 作为的对象的方法调用,this指向对象。
- 作为普通函数调用:
- 严格模式,指向全局对象window
- 非严格:为undefined
call、apply、bind调用,this指向绑定的对象。 - 作为构造函数调用,如使用new,this指向new出来的新对象。
类上下文
this指向类。在类的构造函数中,this是一个常规对象类中所有非静态方法都会被添加到this的原型中。
箭头函数
箭头函数是不绑定this的,它的this来源于上级作用域。
this与封闭词法环境的this保持一致。在全局代码中,它将被设置为全局对象。
var window = this;
var foo = (() => this);
console.log(foo()===window); // true
这里调用foo函数,因为箭头函数不绑定this,所以去foo函数的上级查找this,找到了全局对象window。
原型链中的this
如果该方法存在于一个对象的原型链上,this指向调用这个方法的对象。
var o={
f:function(){
retrun this.a+thia.b;
}
};
var p = Object.creat(0);
p.a = 1;
p.b = 4;
console.log(p.f()); // 5 此时this指向p
作为一个DOM事件处理函数
当函数被用作事件处理函数时,它的this指向触发事件的元素。
function bluify(e){
console.log(this === e.currentTarget); // true
this.style.backgroundColor = 'blue';
}
// 获取id为test的Button
let testButton = documnet.getElementsById('test');
// 将bluify作为元素的点击监听函数
testButton.addEventListener('click',bluift,false);
getter和setter中的this
都会把this绑定到设置或获取属性的对象。
var o={
a:1,
b:2,
getSum(){
return (this.a+this.b)
}
};
console.log(o.sum); // 输出3