0

Which is the best way to reference a private method from returned object in javascript? I leave you some sample code:

var HelloWorld = (function(){
    var hello = function(){
        console.log("hello")
    },
    return{
        addToList: function(){
            //how can i reference hello from here dynamically like:
                            //this["hello"] or this["hell" + "o"]
        }       
    }
})()
3
  • 1
    Have you tried it? What happened? this['hello'](); seems fine to me... Commented Jan 18, 2013 at 18:54
  • BTW, you got a syntax error, you should have a semicolon after the hello function declaration, not a comma. Commented Jan 18, 2013 at 18:55
  • 2
    Not sure if you're having problems with this as well, but the , before the return/after the hello function should be a ;. Commented Jan 18, 2013 at 18:57

5 Answers 5

2

Because the return is still inside the closure, you can just call hello directly. So:

hello();

To make it "dynamic", as the other answers recommend, you need to save hello to something. If you want to attach it to this instead of another object, you just need to store off a reference to this so you can access it later.

var HelloWorld = (function(){
  var self = this;
  this.hello = function(){
    console.log("hello")
  };
  return {
    addToList: function(){
        self["hello"]();
    }       
  }
})();
Sign up to request clarification or add additional context in comments.

1 Comment

This is correct except for what I read in the OP's sample code comment. It mentions that "dynamic" access is requested, which I assume means a string is given and is used to reference the function.
1

hello() is not a method. It's just a function in a closure. So, you can just call it from within your addToList() method.

If you want the hello function to behave like a method with this set to the object instance, you'd have to pass the instance to it as in this example.

var HelloWorld = (function(){
    var hello = function(){
        console.log("hello")
    },
    return{
        addToList: function(){
            //how can i reference hello from here dynamically like:
            hello.call(this);
        }       
    }
})()

If what you're really trying to do is to access the hello function by a string reference, you cannot easily access local variables by string name. If you wanted to do that, you could have to put the hello function into a local object like this:

var HelloWorld = (function(){
    var locals = {
        hello: function(){
            console.log("hello")
        }
    };
    return{
        addToList: function(){
            //how can i reference hello from here dynamically like:
            locals["hello"].call(this);
        }       
    }
})()

2 Comments

Giving you a +1 as you posted an edit at the same time I was posting an answer, and we arrived at the same conclusion.
@JAAulde - I would say that the OP's question is not perfectly clear so I provided a couple different possible answers.
1

As is, you cannot reference the function hello "dynamically" as mentioned in the comment of your sample code. (I am assuming your definition of "dynamically" is to be given a string containing the word "hello" and somehow use it to reference the function hello.)

You could, however, move hello into an object and reference it off that object using square bracket notation:

var HelloWorld = (function () {
    var privateCode = {
        hello: function () {
            console.log('hello');
        }
    };

    return {
        addToList: function () {
            // access via `privateCode['hello']()`
        }       
    };
}());

Comments

1

You can't use this, because you haven't made it a part of the object.

var HelloWorld = (function () {

    var hello = function () { console.log("hello"); };

    return {
        addToList : function () { hello(); }
    };

}());

That will work fine.

If you need to access it by using a string, then you need to make hello, then you have two options:

1) make a public function, which you CAN call with a string, which calls hello

return {
    command : function (string) { if (this[string]) { this[string](); },
    sayHello : function () { hello(); }
};

2) make a private object, which stores your methods (then you can call it with a string):

var private_actions = {
    hello : function () { console.log("hello"); }
};

return {
    command : function (string) {
        if (private_actions[string]) { private_actions[string](); }
    }
};

Comments

1

Since hello only exists in the scope of an anonymous IIFE, you'd need to store it some intermediate object in order to be able to dynamically access hello from a public method:

var HelloWorld = (function(){
    var privates = {
        hello: function (){
            console.log("hello")
        }
    };

    return {
        addToList: function (){
            privates['hello']();
        } 
    }
})();

HelloWorld.addToList();

Working Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.