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"]
}
}
})()
hello()is not a method. It’s just a function in a closure. So, you can just call it from within youraddToList()method.If you want the
hellofunction to behave like a method withthisset to the object instance, you’d have to pass the instance to it as in this example.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: