JS中this的9种指向详解(web前端开发javascript语法基础)
warning:
这篇文章距离上次修改已过440天,其中的内容可能已经有所变动。
在JavaScript中,this的指向是在运行时基于函数的调用方式动态确定的。这里提供了this可能指向的9种情况,以及如何确定this的指向的规则:
- 默认绑定:在未使用任何绑定的情况下,
this指向全局对象,在浏览器中通常是window对象。
function foo() {
console.log(this); // 输出 window 对象
}
foo();- 隐式绑定:调用函数的对象将成为
this。
let obj = {
foo: function() {
console.log(this); // 输出 obj 对象
}
};
obj.foo();- 显式绑定:使用
call或apply可以显式指定this的值。
let obj = {
foo: function() {
console.log(this); // 输出 obj2 对象
}
};
let obj2 = { bar: obj.foo };
obj2.bar.call(obj);- new绑定:使用
new关键字创建对象时,新创建的对象将成为this。
function Foo() {
console.log(this); // 输出 Foo 的实例对象
}
let foo = new Foo();- 箭头函数绑定:箭头函数没有自己的
this,它会捕获其所在上下文的this值。
let obj = {
foo: function() {
return () => {
console.log(this); // 输出 obj 对象
};
}
};
let arrowFunction = obj.foo();
arrowFunction();- 构造器、静态方法、方法和属性:类的构造器中,
this指向新创建的实例对象;类的静态方法中,this指向类本身;类的实例方法中,this指向调用方法的实例;类的实例属性中,不存在this。
class MyClass {
constructor() {
console.log(this); // 输出 MyClass 的实例
}
static staticMethod() {
console.log(this); // 输出 MyClass 类本身
}
instanceMethod() {
console.log(this); // 输出 MyClass 的实例
}
}
let myInstance = new MyClass();
myInstance.instanceMethod();
MyClass.staticMethod();- 回调函数中的
this:回调函数中的this通常指向全局对象,除非使用.bind()来改变。
let obj = {
foo: function() {
console.log(this); // 输出 obj 对象
}
};
setTimeout(obj.foo, 100); // 输出 window 对象
setTimeout(obj.foo.bind(obj), 100); // 输出 obj 对象- DOM事件处理函数中的
this:事件处理函数中的this通常指向触发事件的DOM元素。
document.getElementById('myButton').addEventListener('click', function() {
console.log(this); // 输出 myButton 的 DOM 元素
});- 字符串上下文中的
this:在字符串模板中,this的行为与普通函数中的this一致。
let obj = {
value: 'Hello, World!'
};
let greeting = `${function() {
console.log(this); // 输出 obj 对象
}.call(obj)}`;以上9种情况涵盖了this可能指向的大部
评论已关闭