Skip to content

Instantly share code, notes, and snippets.

@lsmith
Created September 11, 2009 21:37
Show Gist options
  • Save lsmith/185604 to your computer and use it in GitHub Desktop.
Save lsmith/185604 to your computer and use it in GitHub Desktop.
function Foo() {
/* constructor stuff */
}
// apply a class prototype that includes private and public methods
(function () {
function private(x) {
return x + 1;
}
function wouldBePrivate() {
return "I can't be overridden";
}
Foo.prototype = {
public: function (n) {
return "The answer is " + private(n);
},
protected: wouldBePrivate, // but now it's not
usesProtected: function () {
return "I said: " + wouldBePrivate();
},
usesAPIToProtected: function () {
return "Whaddayano, " + this.protected();
}
};
})();
var f = new Foo();
f.public(41); // The answer is 42
f.protected(); // I can't be overridden
f.usesProtected(); // I said I can't be overridden
f.usesAPIToProtected(); // Whaddayano, I can't be overridden
f.protected = function () {
return "I've been overridden!!!";
}
f.usesProtected(); // I said I can't be overridden
f.usesAPIToProtected(); // Whaddayano, I've been overridden!!!
// Alternately
var Foo;
(function () {
Foo = function () {...}
// private/protected functions here
Foo.prototype = { ... }
})();
// or
var Foo = (function () {
function Foo() {...}
// private/protected functions here
Foo.prototype = {...}
return Foo;
})();
// or (don't do this one)
var Foo = new function () {
function Foo() {...}
// private/protected functions here
Foo.prototype = {...}
return Foo;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment