Skip to content

Instantly share code, notes, and snippets.

@davidvandusen
Created March 23, 2015 23:55
Show Gist options
  • Save davidvandusen/3a5cb9b10fbdf9edfdcb to your computer and use it in GitHub Desktop.
Save davidvandusen/3a5cb9b10fbdf9edfdcb to your computer and use it in GitHub Desktop.
JS Closures and Prototypal Inheritance Breakout
var something = 'outer';
var outerSecret = (function () {
for (var i = 10; i--;) {
var mysecretthing = 'shhhhh';
console.log(i + ' ' + something);
}
return mysecretthing;
});
console.log(outerSecret());
//console.log(i); // breaks
function hi() {
console.log(hi.myProp);
}
hi.myProp = 'hello';
hi();
function add(x) {
console.log('the bound value is ' + x);
function adder(y) {
console.log('the passed value is ' + y);
return x + y;
}
return adder;
}
console.log(add(5)(7));
var adderOfFive = add(5);
console.log(typeof adderOfFive);
console.log('-----------------');
var twelve = adderOfFive(7);
console.log(typeof twelve);
console.log('=================');
console.log(twelve);
// You might have seen this surrounding other developers' JS files
(function ($, window, undefined) {
})(jQuery, window);
function Enemy() {
console.log('setting up enemy ' + this.name);
this.alive = true;
}
Enemy.prototype.teeth = false;
function Goomba(name) {
this.name = name;
Enemy.call(this);
this.move = function () {
// moves the goomba
};
}
Goomba.prototype.__proto__ = Enemy.prototype;
var goomba = new Goomba();
console.log(goomba.teeth);
console.log(goomba instanceof Goomba);
console.log(goomba instanceof Enemy);
console.log(goomba instanceof Object);
function SomeNewThing () {}
Enemy.prototype.__proto__ = SomeNewThing.prototype;
console.log(goomba instanceof SomeNewThing);
//Goomba.prototype = null;
//
//console.log(goomba instanceof Enemy);
//console.log(new Goomba() instanceof Enemy);
function Koopa() {
this.name = 'koopa';
Enemy.call(this);
this.move = function () {
// moves the koopa
}
}
Koopa.prototype.__proto__ = Enemy.prototype;
Goomba.prototype.color = 'brown';
var g = new Goomba('goomba');
new Goomba('goo');
new Goomba('boom');
new Goomba('gum');
new Goomba('boog');
new Goomba('asdf');
new Goomba('qwer');
new Goomba('poiu');
var k = new Koopa();
console.log(g.alive);
console.log(k.alive);
console.log(g.color);
console.log(k.color);
var theGoomba = new Goomba();
var theOtherGoomba = new Goomba();
console.log(theGoomba.alive);
Goomba.prototype.color = 'brown';
theOtherGoomba.color = 'blue';
console.log(theGoomba.color);
console.log(theOtherGoomba.color);
console.log(theGoomba.toString());
function Thing() {}
var thing = new Thing();
console.log(thing instanceof Thing);
thing.__proto__ = {};
// Thing.prototype is no longer up thing's prototype chain
console.log(thing instanceof Thing);
console.log(thing instanceof Object);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment