Skip to content

Instantly share code, notes, and snippets.

@listochkin
Created December 19, 2012 11:04
Show Gist options
  • Save listochkin/4335974 to your computer and use it in GitHub Desktop.
Save listochkin/4335974 to your computer and use it in GitHub Desktop.
Private members in JavaScript

Private members in JavaScript

var secretHolder = (function () {
var secret;
return {
getSecret: function () { return secret; },
setSecret: function (newSecret) { secret = newSecret };
}
}());
secretHolder.setSecret('ha-ha');
console.log(secretHolder.getSecret()); // prints ha-ha
console.log('secret' in secretHolder); // prints false
var User = (function () {
var wrap = function (prefix, s, postfix) {
if (!postfix) postfix = prefix;
return prefix + s + postfix
};
function User(name, email) {
this.name = name;
this.email = email;
}
User.prototype.toString = function () {
return wrap('"', this.name) + ' ' + wrap('<', this.email, '>');
};
return User;
}());
var user = new User('John Doe', '[email protected]');
console.log('' + user); // prints "John Doe" <[email protected]>
console.log('wrap' in user || 'wrap' in User); // prints false
// http://nodejs.org/api/modules.html
// -- user.js --
var wrap = function (prefix, s, postfix) {
if (!postfix) postfix = prefix;
return prefix + s + postfix
};
function User(name, email) {
this.name = name;
this.email = email;
}
User.prototype.toString = function () {
return wrap('"', this.name) + ' ' + wrap('<', this.email, '>');
};
module.exports = User;
// -- app.js --
var User = require('./user.js');
var user = new User('John Doe', '[email protected]');
console.log('' + user); // prints "John Doe" <[email protected]>
console.log('wrap' in user || 'wrap' in User); // prints false
// http://requirejs.org/docs/whyamd.html
// -- user.js --
define('user', function () {
var wrap = function (prefix, s, postfix) {
if (!postfix) postfix = prefix;
return prefix + s + postfix
};
function User(name, email) {
this.name = name;
this.email = email;
}
User.prototype.toString = function () {
return wrap('"', this.name) + ' ' + wrap('<', this.email, '>');
};
});
// -- app.js --
define('app', function (require) {
var User = require('user');
var user = new User('John Doe', '[email protected]');
console.log('' + user); // prints "John Doe" <[email protected]>
console.log('wrap' in user || 'wrap' in User); // prints false
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment