码迷,mamicode.com
首页 > 编程语言 > 详细

"this" in javascript

时间:2014-07-18 20:14:34      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:style   blog   java   color   os   art   

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,布布扣,bubuko.com

"this" in javascript

标签:style   blog   java   color   os   art   

原文地址:http://www.cnblogs.com/zhongmi/p/3850291.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!