Skip to content

Instantly share code, notes, and snippets.

@davisford
Created June 17, 2012 14:43
Show Gist options
  • Save davisford/2944726 to your computer and use it in GitHub Desktop.
Save davisford/2944726 to your computer and use it in GitHub Desktop.
JavaScript scope - demo showing JS private, privileged, etc. scope
var FooWrapper = (function() {
// private module scope, shared among all Foo instances
var _private1 = "private1";
var _private3 = "private3";
var Foo = function(arg1, arg2, arg3) {
// private instance var, only visible to privileged methods
var _private2 = "private2";
var _private4 = arg2 + " " + arg3;
// public var; available to anyone anywhere
this.arg1 = arg1;
// private module scope + shared among all instances
// multiple constructor calls will overwrite this
_private3 = arg1;
this.getPrivileged1 = function() {
return _private1 + _private2;
}
this.getPrivileged2 = function() {
return _private4;
}
this.getPrivileged3 = function() {
process.nextTick(function() {
console.log("in callback => ");
console.log("\t _private1: ", _private1);
console.log("\t _private2: ", _private2);
console.log("\t _private3: ", _private3);
console.log("\t _private4: ", _private4);
console.log("\t ");
})
}
}
Foo.prototype.getPublic1 = function() {
// _private2, _private4 is undefined
return _private1;
}
Foo.prototype.getPublic2 = function() {
return _private3;
}
// hangs off the class; public
Foo.classproperty = "zing";
return Foo;
})();
module.exports = FooWrapper;
// written for mocha
var Foo = require('./foo.js')
, sinon = require('sinon')
, should = require('should')
, util = require('util');
describe("Foo", function() {
it("should access privileged / public methods", function(done) {
var foo = new Foo();
foo.getPrivileged1().should.eql('private1private2');
foo.getPublic1().should.eql('private1');
should.not.exist(foo.getPublic2());
should.not.exist(foo.arg1);
var foo2 = new Foo("a", "b", "c");
foo2.arg1.should.eql("a");
// this will overwrite the shared variable
var foo3 = new Foo("1", "2", "3");
foo3.arg1.should.eql("1");
// foo3 constructor overwrites foo2's arg "a"
foo2.getPublic2().should.eql("1");
foo2.arg1.should.eql("a");
foo3.getPublic2().should.eql("1");
foo3.arg1.should.eql("1");
foo.getPrivileged3();
foo2.getPrivileged3();
foo3.getPrivileged3();
done();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment