In Javascript, the key work "this" is a hard point to understand, in this artical, I will try to explain it
talking about "this", we have to talk about closure and the way function is called in Javascript.
function have for kinds of calling:
1. called as a method:
1 var s = { 2 a : ‘123‘, 3 foo:function(){ 4 return this.a 5 } 6 } 7 8 s.foo() //a
in this code, the function is called as object‘s method, in the closure of the function ,this point to its parent object.
2. called as a function
1 var foo = function(){ 2 return this.a 3 } 4 foo() // if a is define in the gloable, return a, else, return undefined.
in this code, the function is called as a function, in the code‘s closure, this will point to the gloable window.
3. called as a constructor
1 var Foo = function(){ 2 this.a = 1; 3 this.b = 2; 4 return this; 5 } 6 7 var foo = new Foo(); 8 foo.a //1;
in this code, the function is called as a constructor, this will point to the new object.
4. called by .apply and .call
1 var foo = function(arg1){ 2 this.a = arg1; 3 } 4 var s = {}; 5 foo.apply(s,[1]);
in this code, when the apply is called, this will be binded to the first param of the apply.
"this" in javascript