- 普通函数调用:
- this指向:在非严格模式下,指向全局对象(浏览器中是
window
,Node.js中是global
);在严格模式下,this
是undefined
。
- 示例:
// 非严格模式
function normalFunction() {
console.log(this);
}
normalFunction(); // 在浏览器中输出window对象
// 严格模式
function strictNormalFunction() {
'use strict';
console.log(this);
}
strictNormalFunction(); // 输出undefined
- 方法调用:
- this指向:
this
指向调用该方法的对象。
- 示例:
const obj = {
name: 'example',
printThis: function() {
console.log(this);
}
};
obj.printThis(); // 输出obj对象
- 构造函数调用:
- this指向:
this
指向新创建的对象实例。
- 示例:
function Person(name) {
this.name = name;
console.log(this);
}
const person = new Person('John'); // 输出新创建的Person实例对象,有name属性为'John'
- apply/call/bind调用:
- this指向:
apply
和call
方法会将函数中的this
绑定到它们的第一个参数上。bind
方法会创建一个新函数,新函数中的this
被绑定到bind
的第一个参数上。
- 示例:
function greet() {
console.log('Hello, I am'+ this.name);
}
const obj1 = { name: 'Alice' };
const obj2 = { name: 'Bob' };
// apply调用
greet.apply(obj1); // 输出Hello, I am Alice
// call调用
greet.call(obj2); // 输出Hello, I am Bob
// bind调用
const newGreet = greet.bind(obj1);
newGreet(); // 输出Hello, I am Alice