"this" in javascript

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() //123

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

var a = 123;
var foo = function() {
	var a = 456;
	return this.a
}
foo() // 123

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.

posted on 2014-07-17 10:02  kunta zhong  阅读(157)  评论(0编辑  收藏  举报

导航