Last active
August 29, 2015 14:14
-
-
Save abrjagad/988d7fb3edd36fe360a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getFunc() { | |
var a = 7; | |
return function(b) { | |
alert(a+b); | |
} | |
} | |
var f = getFunc(); | |
f(5); | |
//12 | |
//Once getFunc() returns, you might think that all of its local variables would be deallocated. | |
//However, that little anonymous function, which alerts to the screen, still has access to the variable a! What gives? | |
//Essentially, getFunc() returns a reference to another, anonymous function. | |
//Later on, we call that function, and it still has access to all of the | |
//variables it had access to at the time of creation. All of these variables that the function has access to at its creation create a closure, which sticks around for as long as the function pointer itself does. | |
//Because of this, when we call f(5), the function is still able | |
//to see that a has a value of 7, and it therefore alerts 12. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Ninja = function(power) { | |
this.abilities.power = power; | |
}; | |
Ninja.prototype.abilities = { | |
power: 100 | |
}; | |
Ninja.prototype.sayPower = function() { | |
alert(this.abilities.power); | |
}; | |
var ninja1 = new Ninja(500); | |
var ninja2 = new Ninja(1000); | |
ninja1.sayPower(); // A | |
ninja2.sayPower(); // B | |
//alerts 1000,1000 | |
//If an object is specified for a property of prototype, | |
//the same object will be referred to in all the instances. | |
//Therefore, ninja1.abilities and ninja2.abilities will refer to the same object, | |
//which means abilities.power of ninja1 also turned out to be 1000, which was set later. | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//weird | |
//but. 'this' refers to the parent of the callee... | |
var x = 3; | |
var foo = { | |
x: 2, | |
baz: { | |
x: 1, | |
bar: function() { | |
return this.x; | |
} | |
} | |
} | |
var go = foo.baz.bar; | |
//the parent of go fn is window | |
alert(go()); //alerts 3 | |
//this could be fixed with below | |
var go = foo.baz.bar.bind(foo.baz); | |
//the parent of bar fn is baz | |
alert(foo.baz.bar());//alerts 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment