Skip to content

Instantly share code, notes, and snippets.

@abrjagad
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abrjagad/bfd2979768d5c184acec to your computer and use it in GitHub Desktop.
Save abrjagad/bfd2979768d5c184acec to your computer and use it in GitHub Desktop.
how "this" keyword behaves
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
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