javascript 中的 this 指向由函数调用方式决定,而非定义位置。1. 默认绑定:普通函数调用时,this 指向全局对象(浏览器中为 window),严格模式下为 undefined;2. 隐式绑定:作为对象方法调用时,this 指向调用该方法的对象,但方法被提取后单独调用会丢失绑定,退回到默认绑定;3. 显式绑定:通过 call、apply 或 bind 方法可显式指定 this 指向;4. new 绑定:使用 new 调用构造函数时,this 指向新创建的实例对象;5. 箭头函数的词法绑定:箭头函数没有自己的 this,其 this 由外层作用域决定,调用方式不影响其指向,从而简化了 this 的管理,尤其在回调函数中避免了上下文丢失问题。理解 this 的核心在于分析函数调用时的执行上下文,掌握这五种绑定规则是解决 this 相关问题的关键,最终 this 的值在运行时根据调用位置动态确定,这一机制体现了 javascript 的灵活性与动态性。

JavaScript 中的
this
this
要真正掌握
this
this
默认绑定 (Default Binding): 当函数作为普通函数独立调用时,
this
window
global
'use strict'
this
undefined
function showThis() {
console.log(this);
}
showThis(); // 在浏览器中输出 Window 对象,在严格模式下输出 undefined
'use strict';
function strictShowThis() {
console.log(this);
}
strictShowThis(); // 输出 undefined隐式绑定 (Implicit Binding): 当函数作为对象的一个方法被调用时,
this
const person = {
name: '张三',
greet: function() {
console.log(`你好,我是 ${this.name}`);
}
};
person.greet(); // 输出:你好,我是 张三 (this 指向 person 对象)但要注意,如果这个方法被“提取”出来单独调用,隐式绑定就会失效,转而使用默认绑定。
const anotherGreet = person.greet; anotherGreet(); // 输出:你好,我是 undefined (或在浏览器中是 "你好,我是 Window")
显式绑定 (Explicit Binding): 通过
call()
apply()
bind()
this
function introduce(age, city) {
console.log(`我是 ${this.name},${age} 岁,来自 ${city}`);
}
const person2 = { name: '李四' };
introduce.call(person2, 30, '北京'); // 输出:我是 李四,30 岁,来自 北京
introduce.apply(person2, [25, '上海']); // 输出:我是 李四,25 岁,来自 上海
const boundIntroduce = introduce.bind(person2, 40);
boundIntroduce('广州'); // 输出:我是 李四,40 岁,来自 广州new 绑定 (New Binding): 当使用
new
this
function Car(make, model) {
this.make = make;
this.model = model;
console.log(this); // 这里的 this 就是新创建的 Car 实例
}
const myCar = new Car('Honda', 'CRV'); // 输出 Car { make: 'Honda', model: 'CRV' }箭头函数 (Arrow Functions) 的词法绑定: 箭头函数没有自己的
this
this
this
const user = {
name: '王五',
logName: function() {
// 这里的 this 指向 user 对象
setTimeout(function() {
console.log(this.name); // 这里的 this 指向全局对象 (或 undefined)
}, 100);
},
logNameArrow: function() {
// 这里的 this 指向 user 对象
setTimeout(() => {
console.log(this.name); // 这里的 this 依然指向 user 对象
}, 100);
}
};
user.logName(); // 输出 undefined (或 Window)
user.logNameArrow(); // 输出 王五在我看来,
this
this
我们常常会遇到这样的情况:一个函数在某个上下文中工作得好好的,但当它作为回调函数被传递出去后,
this
this
this
理解这些规则,尤其是“调用位置决定
this
this
this
.
new
call
apply
bind
箭头函数是 ES6 引入的一个非常棒的特性,它在
this
this
this
this
this
这在处理回调函数,尤其是异步操作的回调时,简直是“救星”。在 ES6 之前,我们为了在
setTimeout
this
var self = this;
bind
// ES5 时代常见的 this 陷阱与解决方案
function Timer() {
this.seconds = 0;
// var self = this; // 方案一:保存 this
setInterval(function() {
// console.log(self.seconds++); // 使用保存的 self
// 或者
// console.log(this.seconds++); // 这里的 this 指向 window/undefined
}.bind(this), 以上就是JS的this关键字怎么用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号