js实现this
理解 this 的基本概念
在 JavaScript 中,this 是一个关键字,指向当前执行上下文中的对象。它的值取决于函数的调用方式,而非定义方式。this 的动态绑定特性是 JavaScript 的核心机制之一。
默认绑定(全局上下文)
当函数独立调用时,this 默认指向全局对象(浏览器中为 window,Node.js 中为 global)。严格模式('use strict')下,this 为 undefined。
function showThis() {
console.log(this);
}
showThis(); // 非严格模式:window;严格模式:undefined
隐式绑定(方法调用)
当函数作为对象的方法调用时,this 指向调用该方法的对象。
const obj = {
name: 'Alice',
greet: function() {
console.log(this.name);
}
};
obj.greet(); // 输出 "Alice"
显式绑定(call/apply/bind)
通过 call、apply 或 bind 方法,可以显式指定 this 的值。

function greet() {
console.log(this.name);
}
const person = { name: 'Bob' };
greet.call(person); // 输出 "Bob"
构造函数绑定(new 调用)
使用 new 调用构造函数时,this 指向新创建的实例对象。
function Person(name) {
this.name = name;
}
const alice = new Person('Alice');
console.log(alice.name); // 输出 "Alice"
箭头函数的 this
箭头函数没有自己的 this,它会继承外层作用域的 this 值。

const obj = {
name: 'Charlie',
greet: () => {
console.log(this.name); // 指向外层 this(如全局对象)
}
};
obj.greet(); // 可能输出 undefined(严格模式)
事件处理函数中的 this
在 DOM 事件处理函数中,this 通常指向触发事件的元素。
button.addEventListener('click', function() {
console.log(this); // 指向 button 元素
});
解决 this 绑定的常见问题
使用 bind 固定 this 的值,避免因调用方式不同而丢失上下文。
const obj = {
name: 'Dave',
greet: function() {
setTimeout(function() {
console.log(this.name); // 默认绑定下 this 可能指向全局
}.bind(this), 100);
}
};
obj.greet(); // 输出 "Dave"
总结
this 的绑定规则优先级从高到低为:
new绑定- 显式绑定(
call/apply/bind) - 隐式绑定(方法调用)
- 默认绑定(全局或
undefined)
箭头函数的 this 由词法作用域决定,无法通过上述规则修改。






