Accessing private member variables from prototype-defined functions

Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?

TestClass = function(){
    var privateField = "hello";
    this.nonProtoHello = function(){alert(privateField)};
};
TestClass.prototype.prototypeHello = function(){alert(privateField)};

This works:

t.nonProtoHello()

But this doesn’t:

t.prototypeHello()

I’m used to defining my methods inside the constructor, but am moving away from that for a couple reasons.

25 Answers
25

Leave a Comment