js实现this
在JavaScript中,this是一个动态绑定的关键字,其值取决于函数的调用方式。以下是几种常见场景下的this绑定规则及实现方法:
全局上下文中的this
在全局作用域或普通函数中,this默认指向全局对象(浏览器中为window,Node.js中为global)。严格模式下('use strict'),this为undefined。
console.log(this); // 浏览器中输出: Window {...}
function example() {
console.log(this); // 非严格模式下输出: Window {...}
}
example();
对象方法中的this
当函数作为对象的方法调用时,this指向调用该方法的对象。
const obj = {
name: 'Object',
logThis() {
console.log(this); // 输出: { name: 'Object', logThis: [Function: logThis] }
}
};
obj.logThis();
构造函数中的this
通过new调用构造函数时,this指向新创建的实例对象。
function Person(name) {
this.name = name;
console.log(this); // 输出: Person { name: 'Alice' }
}
const person = new Person('Alice');
显式绑定this
通过call、apply或bind可以显式设置this的值。
function greet() {
console.log(`Hello, ${this.name}`);
}
const user = { name: 'Bob' };
greet.call(user); // 输出: Hello, Bob
const boundGreet = greet.bind(user);
boundGreet(); // 输出: Hello, Bob
箭头函数中的this
箭头函数不绑定自己的this,而是继承外层作用域的this值。
const obj = {
name: 'Arrow',
logThis: () => {
console.log(this); // 输出: Window {...}(继承自全局作用域)
}
};
obj.logThis();
事件处理器中的this
在DOM事件处理函数中,this通常指向触发事件的元素。

document.getElementById('myButton').addEventListener('click', function() {
console.log(this); // 输出: <button id="myButton">...</button>
});
注意事项
- 箭头函数、
bind等方法会固定this,无法通过call或apply修改。 - 回调函数(如
setTimeout)可能意外丢失this绑定,需通过闭包或bind解决。






