coffeescript(javascript) this 的理解

本文深入探讨了JavaScript中this的复杂概念,解释了其如何根据不同的调用场景指向不同的上下文环境,并提供了实例帮助理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

javascript里面的this其实是不容易理解的,就好像和ruby里面的self一样难理解。但是对于this的理解,也是能晋升动态语言上一级的前提。

目前阅读coffeescript的书,里面对coffeescript的this做了很不错的总结,我认为完全可以适用于javascript。

0. No doubt some of the confusion stems from the word itself; people expectthisto refer to “this object.” Instead, you should think of it as “this context.”

初学者(指js和coffeescript)容易被this弄糊涂的原因,可能就源之于this的字面意识;大家都以为this指的是“this object“(这个对象)。其实,应该理解为”this context“(当前上下文环境)。

1. When the new keyword is put in front of a function call, its context is the new object.

2.  When a function is called with callorapply, the context is the first argu- ment given.

3. Otherwise, if a function is called as an object property (obj.func) orobj['func']), it runs in that object’s context.

4. If none of the above apply, then the function runs in the global context.

 对于4补充下,如果你没有用new来调用constructor,而是以函数方式来调用,就会出问题,如下例所示:

var Person = function(name){ this.name = name; }

//don't do this
var p = Person('Bob');
你会得到p是undefined, 而且windows多了一个属性name(或者说你多了一个全局变量name,其值是‘Bob')。究其原因,就是作为一般函数调用时,this所指为windows。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值