Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?
TestClass = function(){
var priv
There's a simpler way by leveraging the use of bind and call methods.
By setting private variables to an object, you can leverage that object's scope.
function TestClass (value) {
// The private value(s)
var _private = {
value: value
};
// `bind` creates a copy of `getValue` when the object is instantiated
this.getValue = TestClass.prototype.getValue.bind(_private);
// Use `call` in another function if the prototype method will possibly change
this.getValueDynamic = function() {
return TestClass.prototype.getValue.call(_private);
};
};
TestClass.prototype.getValue = function() {
return this.value;
};
This method isn't without drawbacks. Since the scope context is effectively being overridden, you don't have access outside of the _private object. However, it isn't impossible though to still give access to the instance object's scope. You can pass in the object's context (this) as the second argument to bind or call to still have access to it's public values in the prototype function.
function TestClass (value) {
var _private = {
value: value
};
this.message = "Hello, ";
this.getMessage = TestClass.prototype.getMessage.bind(_private, this);
}
TestClass.prototype.getMessage = function(_public) {
// Can still access passed in arguments
// e.g. – test.getValues('foo'), 'foo' is the 2nd argument to the method
console.log([].slice.call(arguments, 1));
return _public.message + this.value;
};
var test = new TestClass("World");
test.getMessage(1, 2, 3); // [1, 2, 3] (console.log)
// => "Hello, World" (return value)
test.message = "Greetings, ";
test.getMessage(); // [] (console.log)
// => "Greetings, World" (return value)