Search code examples
javascriptconstructorprivatepublic

setting public property in a private function executed on initialization Javascript


I have an object with

myObj = function(){
    this.myPublicMember = null;
    function privateInitFunc(){
         this.myPublicMember = "blah blah test";
    }

    privateInitFunc()
}

myObj.prototype = {
    getPublicMember: function(){ console.log(this.myPublicMember) }
}

and I instantiate like:

 var a = new myObj();
 a.getPublicMember // logs Null!

How do I set a public property in a private function executed on initialization? I need the private initialization function because there are some other variables there that are obtained before setting the myPublicMember


Solution

  • You should set the context when you call the function:

    privateInitFunc.call(this)