Last active
September 5, 2017 18:48
-
-
Save nate-getch/64c6e4ff0c32afae2c7d16574f5738da to your computer and use it in GitHub Desktop.
js code accessing var in objects of different level
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 a = "one"; | |
var obj = { | |
a:"two", | |
b: { | |
a:"three", | |
fn: function(){ | |
return this.a; | |
} | |
} | |
} | |
var t1 = obj.b.fn; | |
console.log(t1()); // the function is being invoked in global scope, hence, 'this' will refer to window object, output 'one' | |
var t2 = obj.b.fn(); // the function is being invoked and assigned to t2 var | |
console.log(t2); // output 'three' | |
// what if we want to refer to 'a' var in the first level obj | |
console.log(t1.call(obj)); // output 'two' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment