首页 > 解决方案 > How to make "this" in nested function refer to parent object or what is the best practice to this problem?

问题描述

From example code below I'm trying to add a method inside an object where it generates new name based on object properties but "this" in this context is referring global object but not the parent one

It's ok using arrow function but the functions won't be hoisted and I need to express the function before using it. I prefer knowing what it does before seeing the code.

using arrow function expression it does work but is not hoisted using function declaration it doesn't work but is hoisted

Is there any best practice approach to this kind of problem?

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"

标签: javascript-objects

解决方案


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

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

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"

推荐阅读