Skip to content

Instantly share code, notes, and snippets.

@nate-getch
Last active September 5, 2017 18:48
Show Gist options
  • Save nate-getch/64c6e4ff0c32afae2c7d16574f5738da to your computer and use it in GitHub Desktop.
Save nate-getch/64c6e4ff0c32afae2c7d16574f5738da to your computer and use it in GitHub Desktop.
js code accessing var in objects of different level
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