JavaScript无法访问同级方法

JavaScript cannot access sibling method

本文关键字:方法 访问 JavaScript      更新时间:2023-09-26

给定以下内容,我如何使其正确工作?

return {
    methodA: function() {
        return methodB();
    },
    methodB: function() {
        alert("hi");
    }
}

您需要通过this引用上下文。

var foo = {
    methodA: function() {
        return this.methodB(); //context
    },
    methodB: function() {
        alert("hi");
    }
}
foo.methodA(); //alerts "hi"

您似乎是从类似模块的函数返回的。安全的方法是不使用this,而是保留对对象的引用,这样函数的调用方式就无关紧要了。

function getObj() {
  var obj = {
    methodA: function() {
      return obj.methodB();
    },
    methodB: function() {
        alert("hi");
    }
  };
  return obj;
}
var myObj = getObj();
// Works
myObj.methodA();
// Works but would not work if you were using `this` as suggested by Utkanos.
someDomElement.addEventListener('click', myObj.methodA);