Skip to content

Instantly share code, notes, and snippets.

@CrabDude
Created February 8, 2011 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CrabDude/817301 to your computer and use it in GitHub Desktop.
Save CrabDude/817301 to your computer and use it in GitHub Desktop.
Private.js Example: Inheritable Private Instance Members
// Class.extend takes a function that returns the options object
// it is passed the accessor function generated in the Pvt.js example above
var Person = Class.extend(function(pvt) {
// private static member
var species = "Homo sapien";
return {
init: function(isDancing) {
// pvt(this).invisible === undefined
// pvt(this).hasSword === undefined
pvt(this).dancing = isDancing;
// pvt(this).dancing === isDancing
},
dance: function() {
return pvt(this).dancing;
},
getSpecies: function() {
return species ;
}
};
});
var Ninja = Person.extend(function(pvt) {
return {
init: function(hasSword){
pvt(this).invisible = true;
this._super( false );
pvt(this).hasSword = hasSword || true;
// pvt(this).dancing === false
},
dance: function(){
// Call the inherited version of dance()
return this._super();
},
swingSword: function(){
return pvt(this).hasSword;
}
};
});
var p = new Person(true);
p.dance(); // => true
var n = new Ninja();
n.dance(); // => false
n.swingSword(); // => true
// Should all be true
p instanceof Person && p instanceof Class &&
n instanceof Ninja && n instanceof Person && n instanceof Class;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment