微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使嵌套函数中的“this”引用父对象或此问题的最佳实践是什么?

如何解决如何使嵌套函数中的“this”引用父对象或此问题的最佳实践是什么?

来自下面的示例代码 我正在尝试在一个对象中添加一个方法,它根据对象属性生成名称 但是在这种情况下,“this”指的是全局对象,而不是父对象

使用箭头函数可以,但是函数不会被提升,我需要在使用之前表达函数。我更喜欢在看到代码之前先了解它的作用。

使用箭头函数表达式它确实有效但没有提升 使用函数声明它不起作用但被提升

是否有解决此类问题的最佳实践方法

const agent = {
  firsName: "John",lastName: "Depp",born: 12/04/1987,secretName: function() {

      return newFirstName() + newLastName()
    
    function newFirstName() {

      // complex codes here

      return "Agent " + this.firstName // for simplicity
      }
    
    function newLastName() {

      // complex codes here

      return "Agent " + this.LastName // for simplicity
    }
  },};

console.log(agent.secretName()) // logs  "Agent undefinedAgent undefined"

解决方法

这可能是由于您的函数的词法范围。您可以阅读有关它的更多信息 herehere

因此,如果您将辅助函数上移一级,问题就解决了:

const agent = {
  firstName: 'John',lastName: 'Depp',born: 12 / 04 / 1987,newFirstName: function () {
    // complex codes here

    return 'Agent ' + this.firstName; // for simplicity
  },newLastName: function () {
    // complex codes here

    return 'Agent ' + this.lastName; // for simplicity
  },secretName: function () {
    return this.newFirstName() + this.newLastName();
  },};

console.log(agent.secretName()); // logs  "Agent undefinedAgent undefined"
,

您应该使用箭头函数,以便它们可以定位其父作用域。

const agent = {
  firstName: "John",lastName: "Depp",born: 12/04/1987,secretName: function() {
        const  newFirstName = () => {
      return "Agent " + this.firstName;
      }
    const newLastName = ()  => {
      return " Agent " + this.lastName;
      }
    
    return newFirstName() + newLastName();
  },};
console.log(agent.secretName())
,

好的,我从这个帖子中找到了答案How to access the correct `this` inside a callback?

简而言之:只定义外部作用域 让 self = this

示例

const agent = {
  firstName: "John",secretName: function() {
    const self = this;
    
      return newFirstName() + newLastName()
    
    function newFirstName() {
      return "Agent " + self.firstName 
      }
    function newLastName() {
      return "Agent " + self.lastName 
   }
  }
}

console.log(agent.secretName()) // logs JohnJohn it works!!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。