Created
February 17, 2012 12:16
-
-
Save nulltask/1853023 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 User() { | |
| // constructor. | |
| } | |
| User.prototype.publicFn = function() { | |
| // call private function. | |
| this._privateFn(); | |
| }; | |
| User.prototype._privateFn = function() { | |
| // this is private function. | |
| }; | |
| var user = new User(); | |
| user.publicFn(); | |
| user._privateFn(); // damn, It's callable... |
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 User() { | |
| // constructor. | |
| } | |
| !function(proto) { | |
| function _privateFn() { | |
| // this is private function. | |
| } | |
| proto.publicFn = function() { | |
| // call private function. | |
| _privateFn(); | |
| }; | |
| }(User.prototype); | |
| var user = new User(); | |
| user.publicFn(); | |
| user._privateFn(); // yeah, throws exception! |
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 User() { | |
| // constructor. | |
| } | |
| !function(proto) { | |
| function _privateFn() { | |
| // what is `this`? | |
| this.is = 'it'; | |
| return Object.prototype.toString.call(this); | |
| } | |
| proto.publicFn1 = function() { | |
| // call private function. | |
| console.log(_privateFn()); // [object global] | |
| }; | |
| proto.publicFn2 = function() { | |
| // call private function with `call()` | |
| console.log(_privateFn.call(this)); // [object Object] | |
| }; | |
| }(User.prototype); | |
| var user = new User(); | |
| user.publicFn1(); | |
| console.log(user.is); // `undefined` ... wtf? | |
| console.log(is); // `it` ... aarrrghh!! global leak! | |
| user.publicFn2(); | |
| console.log(user.is); // `it` ... yeah! |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://null.ly/post/17762856703/javascript-private-method