質問

:I have a javascript class written in the 'revealing module pattern':

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,
         };
} ();

as you can see in 'this' inside 'methodB' does not recognize private methods of the class.

Edit: My intention was to call a helper private method from a public class. Within this private class I needed 'this'. If I call 'methodA("a")' directly from 'methodB' (without 'that') I do not have 'this' ('this' will be global context). The solution will be:

methodA.call(this, "a");
役に立ちましたか?

解決

First of all you have error in

return {
    methodB = methodB,
    methodC = methodC,
}

It should be

 return {
    methodB : methodB,
    methodC : methodC
}

In your example you have

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

that=this and the keyword this refers to current object and you have returned an object with methodBandmethodC but in your object you don't havemethodAso that.methodA("a")is not working insidemethodBbecausemethodAis not the part of your current object but if you were wrote it like

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

Then it would have run.

that=thisandthis=myObjectand myObjecthas only two methods methodBandmethodC so that.methodA("a") which means myObject.methodA("a") should not run because it doesn't exist in myObject

DEMO-1 and DEMO-2

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top