在 JavaScript 中,如何从更深的嵌套方法中引用方法的 return 值

In JavaScript, How to reference the return value of a method from a deeper nested method

两个上下文中this的值是多少,一个嵌套函数如何引用另一个函数的返回值?

var rootObj = {
    nestedObjA: {
        functionA: function() {
            // what is value of 'this' here?
            return 'foo';
        }
    },
    nestedObjB: {
        functionB: function() {
            // how to reference? >> rootObj.nestedObjA.functionA
            // what is the value of 'this' here?
        }
    }
}

两个函数中 this 的值应分别为 rootObj.nestedObjA.functionArootObj.nestedObjB.functionB。要检查 this 的值,可以在每个函数中添加 console.dir(this)

要return一个函数的值,你应该在函数体中添加return,例如; return rootObj.nestedObjA.functionA()rootObj.nestedObjB.functionB

var rootObj = {
    nestedObjA: {
        functionA: function() {
            // what is value of 'this' here?
            console.dir(this);
            return 'foo';
        }
    },
    nestedObjB: {
        functionB: function() {
            // how to reference? >> rootObj.nestedObjA.functionA
            // what is the value of 'this' here?
            console.dir(this);
            return rootObj.nestedObjA.functionA()
        }
    }
}

var res = rootObj.nestedObjB.functionB();
console.log(res); // 'foo'

无法保证 "What is the value of this inside of a function?" 的答案,因为您可以使用函数原型的 apply()/call() 方法进行设置。

var rootObj = {
  nestedObjA: {
    functionA: function() {
      var foo = "bar";
      return foo;
    }
  },
  nestedObjB: {
    functionB: function() {
      var foo = this.nestedObjA.functionA();
      console.log(foo);
    }
  }
}

// When calling functionB() you could use:
rootObj.nestedObjB.functionB.apply(rootObj);

this的值默认是functionB的函数范围;