Skip to content

Instantly share code, notes, and snippets.

@ahirschberg
Last active August 29, 2015 14:18
Show Gist options
  • Select an option

  • Save ahirschberg/818752e70be9655b20fb to your computer and use it in GitHub Desktop.

Select an option

Save ahirschberg/818752e70be9655b20fb to your computer and use it in GitHub Desktop.
Shows variable/function scope in JavaScript
function Foo(args) {
var private_variable = args.private_var;
this.public_variable = args.public_var;
this.public_method = function () { };
function private_method() { }
}
function Foo() {
this.doOneThing = function () { return 'one done.'; };
}
var foo = new Foo();
function Bar() {
this.doAnotherThing = function () { return 'another done.'; };
}
var bar = new Bar();
bar.doOneThing() //=> TypeError: undefined is not a function (#doOneThing is undefined)
bar.doAnotherThing() //=> 'another done.'
Bar.prototype = foo; // Prototyping is like inheritance, but more flexible
// Can't do Bar.prototype Foo(), must use an actual instance, like foo or new Foo()
bar.doOneThing() //=> same TypeError as before
var bar2 = new Bar();
bar2.doOneThing(); //=> 'one done.' -- It works!
bar2.doAnotherThing() //=> 'another done.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment