在 JavaScript 中,如何从更深层次的嵌套方法引用方法的返回值

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

本文关键字:方法 深层次 返回值 嵌套 引用 JavaScript      更新时间:2023-09-26
两个

上下文中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的值是多少?"没有保证的答案,因为您可以使用函数原型的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 的函数作用域;

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

要从函数返回值,您应该在函数体中添加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'