1

:我有一个用“显示模块模式”编写的 javascript 类:

myObject = function () {
    var varA,
        varB,

        methodA = function (data) {

            //Some code...
        },
        methodB = function (data) {
             var that = this;
             that.methodA("a"); // --> 'that' recognize only public methods: 'methodB' / 'methodC' !!!
        },
        methodC = function (data) {

        };
        return {
            methodB : methodB,
            methodC : methodC,
         };
} ();

正如您在“methodB”中的“this”中看到的那样,它不识别类的私有方法。

编辑: 我的意图是从公共类中调用一个辅助私有方法。在这个私人课程中,我需要“这个”。如果我直接从 'methodB' 调用 'methodA("a")'(没有 'that')我没有 'this'('this' 将是全局上下文)。解决方案将是:

methodA.call(this, "a");
4

1 回答 1

4

首先你有错误

return {
    methodB = methodB,
    methodC = methodC,
}

它应该是

 return {
    methodB : methodB,
    methodC : methodC
}

在您的示例中,您有

methodB = function (data) {
         var that = this;
         that.methodA("a");
    }

that=this并且关键字this是指当前对象,并且您已经返回了一个对象,methodB但是methodC在您的对象中您没有,methodA所以that.methodA("a")不能在内部工作,methodB因为methodA它不是您当前对象的一部分,但是如果您像这样写

methodB = function (data) {
    methodA("a");
}

然后它就会运行。

that=thisand this=myObjectandmyObject只有两种方法methodBmethodC所以that.methodA("a")这意味着myObject.methodA("a")不应该运行,因为它不存在于myObject

DEMO-1DEMO-2

于 2012-06-17T16:18:45.580 回答