Skip to content

Instantly share code, notes, and snippets.

@mikechambers
Created April 12, 2012 19:22
Show Gist options
  • Save mikechambers/2370306 to your computer and use it in GitHub Desktop.
Save mikechambers/2370306 to your computer and use it in GitHub Desktop.
Playing around ideas for prototype based inheritance that also provides private properties.
function Foo()
{
var _a = "hello";
if(!Foo.prototype.bar)
{
Foo.prototype.bar = function()
{
console.log("hi " + _a);
};
Object.defineProperty(
Foo.prototype,
"a",
{
get:function(){
return _a;
},
}
);
}
}
var f = new Foo();
f.bar(); //hi hello
console.log(f._a); //undefined
console.log(f.a); //hello
@mikechambers
Copy link
Author

Actually, this doesnt work.

_a is essentially a private static variable shared between all instances of the class.

The only way I can think to do this, is to bind all of the when the class is instantiated. However, this means you can't use prototype based classes (each instance will have its own copy of functions / properties).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment