1. 作为对象的属性被调用
this指向对象
let object = {
name: 'my name',
test: function() {
console.log(this.name);
}
}
object.test(); // my name
2. 作为普通函数被调用
this总是指向全局对象(浏览器中通常为window);严格模式下,this指向undefined。
// 非严格模式下
let test = function() {
console.log(this); // window
}
test();
// 严格模式下,函数中使用 ES5 的 'use strict'。
let test = function() {
'use strict'
console.log(this); // undefined
}
test();
3. 箭头函数
箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this,即 this 和父级作用域志向相同。
let object = {
test() {
setTimeout(function() {
setTimeout(function() {
console.log(this); // window
})
setTimeout(() => {
console.log(this); // window
})
})
setTimeout(() => {
setTimeout(function() {
console.log(this); // window
})
setTimeout(() => {
console.log(this); // test
})
})
}
}
object.test();
4. 作为构造器调用
通常情况下,this指向被构造函数返回的实例;
例外:如果构造函数显式的返回了一个Object类型的对象,那么结果也会只得到这个对象。
let Test = function(name) {
this.name = name;
console.log(this);
}
let test1 = new Test('张三'); // Test { name: '张三' }
let test2 = new Test('李四'); // Test { name: '李四' }
5. 当一个DOM元素被绑定事件处理函数时,this指向被点击的这个元素
6. call 和 apply 调用
- 作用:动态改变 this 指向,使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数;
- 本质:允许为不同的对象分配和调用属于一个对象的函数或方法;
- 区别:
- call(this, params1, params2, ...)
- apply(this, [params1, params2, ...])
可参考链接:call 和apply的作用与区别