"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.

转载于:https://www.cnblogs.com/zhongmi/p/3850291.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值