返回

此JavaScript词法范围内的this,还有哪些不知道?

前端

在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引用该方法所属的实例。

我希望这篇文章对您有所帮助。如果您有任何问题,请随时在下面发表评论。