Last active
August 29, 2015 14:15
-
-
Save abrjagad/bfd2979768d5c184acec to your computer and use it in GitHub Desktop.
how "this" keyword behaves
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 c(){ | |
return this; | |
} | |
c() //prints window | |
var obj = { | |
a:1, | |
b:2 | |
} | |
c.call(document);// prints document | |
c.call(obj); // prints {a:1,b:2} | |
function d(){ | |
return this.a; | |
} | |
d()//prints undefined | |
d.call(obj);//prints 1 | |
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 = { | |
b: this, | |
c: function() { | |
return this; | |
} | |
} | |
var ob = { | |
a: 1, | |
b: 1 | |
} | |
a.b //prints window | |
a.c() | |
// prints {b:this, c:function(){return this;}} | |
//reference to a, i.e the parent of the method | |
a.b.call(window) // error:: a.b.call is not a function | |
a.c.call(ob); // prints {a:1,b:1} | |
var a = { | |
b: { | |
d: "abe", | |
c: function() { | |
return this.d; | |
} | |
} | |
} | |
a.b.c() //prints "abe" | |
//now | |
var o = { | |
d: "mah" | |
}; | |
a.b.c.call(o) //prints "mah" | |
//let n is undefined | |
a.b.c.call(n) //prints ReferenceError: op is not defined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment