Skip to content

Instantly share code, notes, and snippets.

@nulltask
Created February 17, 2012 12:16
Show Gist options
  • Select an option

  • Save nulltask/1853023 to your computer and use it in GitHub Desktop.

Select an option

Save nulltask/1853023 to your computer and use it in GitHub Desktop.
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...
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!
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!
@nulltask
Copy link
Author

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