JavaScript Prototype and Encapsulation

Posted by Adam Davies on Stack Overflow See other posts from Stack Overflow or by Adam Davies
Published on 2012-11-25T22:05:19Z Indexed on 2012/11/25 23:04 UTC
Read the original article Hit count: 159

Filed under:

Sorry I'm probably being a realy noob here...but:

I have the following javascript object:

jeeni.TextField = (function(){

    var tagId;

    privateMethod = function(){
        console.log("IN: privateMethod");
    }

    publicMethod = function(){
        console.log("IN: publicMethod: " + this.tagId);
    }

    jeeni.TextField = function(id){
        console.log("Constructor");
        this.tagId = id;
    }

    jeeni.TextField.prototype = {
            constructor: jeeni.TextField,
            foo: publicMethod
    };

    return jeeni.TextField;
 }());

Now when I run the following code I get the corresponding result:

var textField1 = new jeeni.TextField(21); // Outputs: Constructor
textField1.foo();           // Outputs: IN: publicMethod: 21
console.log(textField1.tagId); // Outputs: 21
console.log(textField1.privateMethod); // Outputs: undefined

So my question is why is privateMethod hidden and tagId is not. I want them both to be private scope.

Please help a noob.

Thanks

© Stack Overflow or respective owner

Related posts about JavaScript