- 全局作用域中的函数调用:
- this指向:在非严格模式下,全局作用域中的函数调用时,
this
指向全局对象(在浏览器中是window
,在Node.js中是global
)。在严格模式下,this
指向undefined
。
- 原因:在JavaScript的设计之初,为了方便在全局函数中访问全局对象,就将全局函数中的
this
指向全局对象。而严格模式为了更严谨,避免这种默认的全局对象绑定,将其设为undefined
。
- 对象方法调用:
- this指向:
this
指向调用该方法的对象。
- 原因:当一个函数作为对象的方法被调用时,JavaScript内部机制会将该对象作为
this
的值传递给函数,这样函数内部就可以通过this
访问到该对象的属性和其他方法。例如:
let obj = {
name: 'test',
printName: function() {
console.log(this.name);
}
};
obj.printName();//这里的this指向obj
- 使用call、apply方法调用函数:
- this指向:
this
指向call
或apply
方法传入的第一个参数。如果传入null
或undefined
,在非严格模式下,this
会指向全局对象;在严格模式下,this
就是null
或undefined
。
- 原因:
call
和apply
方法的设计目的就是为了改变函数执行时this
的指向。通过将需要绑定的对象作为第一个参数传入,函数在执行时this
就会被绑定为该对象,这样就可以让函数在不同的对象上下文中执行。例如:
function greet() {
console.log('Hello, '+this.name);
}
let person1 = {name: 'Alice'};
let person2 = {name: 'Bob'};
greet.call(person1);//this指向person1
greet.apply(person2);//this指向person2