-
-
Save tivac/185607 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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