返回
此JavaScript词法范围内的this,还有哪些不知道?
前端
2023-11-13 14:44:56
在JavaScript中,this
引用当前执行代码的对象,它可能是全局对象、函数对象或一个自定义对象。this
的值由函数的调用方式决定。
在词法作用域中,this
的值在函数定义时确定。这意味着this
总是引用创建函数的对象,即使函数在其他地方调用也是如此。例如:
function Person(name) {
this.name = name;
this.getName = function() {
return this.name;
};
}
const person = new Person('John Doe');
console.log(person.getName()); // 'John Doe'
Person
函数的getName
方法是在词法作用域中定义的,因此this
引用person
对象。即使我们从另一个对象调用getName
方法,this
仍将引用person
对象。例如:
const anotherObject = {
getName: person.getName
};
console.log(anotherObject.getName()); // 'John Doe'
在动态作用域中,this
的值在函数调用时确定。这意味着this
引用函数被调用的对象。例如:
function Person(name) {
this.name = name;
}
const person = new Person('John Doe');
function getName() {
return this.name;
}
console.log(getName()); // undefined
getName
函数没有显式绑定,因此它使用动态作用域。当从全局作用域调用getName
函数时,this
引用全局对象。因此,getName
函数返回undefined
。
this
是一个复杂的主题,但了解它是如何工作的非常重要。一旦您掌握了this
,您就可以编写更强大和更灵活的JavaScript代码。
箭头函数中的this
箭头函数没有自己的this
值。相反,箭头函数继承其父作用域的this
值。例如:
const person = {
name: 'John Doe',
getName() {
return () => {
return this.name;
};
}
};
console.log(person.getName()()); // 'John Doe'
箭头函数getName
中的this
引用person
对象,因为它是内部函数getName
的子作用域。
类方法中的this
类方法中的this
引用该方法所属的实例。例如:
class Person {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
const person = new Person('John Doe');
console.log(person.getName()); // 'John Doe'
类方法getName
中的this
引用person
实例,因为它是一个类方法。
避免常见的this错误
以下是避免常见this
错误的一些技巧:
- 始终显式绑定this。 这将确保
this
始终引用您想要的对象。 - 了解箭头函数没有自己的this值。 相反,箭头函数继承其父作用域的
this
值。 - 在类方法中,this引用该方法所属的实例。
我希望这篇文章对您有所帮助。如果您有任何问题,请随时在下面发表评论。