Understanding JavaScript this keyword

http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/

Lets start with the ECMAScript definition of this:

The  this keyword evaluates to the value of the  ThisBinding of the current execution context.

from ECMA 5.1, 11.1.1

How is ThisBinding set?

Each function defines a [[Call]] internal method (ECMA 5.1, 13.2.1 [[Call]]) which passes invocation values to the function’s execution context:

The following steps are performed when control enters the execution context for function code contained in function object F, a caller provided thisValue, and a caller provided argumentsList:
1. If the function code is strict code, set the ThisBinding to thisValue.
2. Else if thisValue is null or undefined, set the ThisBinding to the global object.
3. Else if Type(thisValue) is not Object, set the ThisBinding to ToObject(thisValue).
4. Else set the ThisBinding to thisValue

from ECMA 5.1, 10.4.3 Entering Function Code (slightly edited)

In other words ThisBinding is set to the object coercion of the abstract argument thisValue, or ifthisValue is undefined, the global object (unless running in strict mode in which case thisValue is assigned to ThisBinding as-is)

So where does thisValue come from?

Here we need to go back to our 5 types of function invocation:

1. Invoke as a method
2. Invoke as baseless function call

in ECMAScript parlance these are Function Calls and have two components: a MemberExpression and an Arguments list.

1. Let ref be the result of evaluating MemberExpression.
2. Let func be GetValue(ref).
6. If Type(ref) is Reference, then
  a. If IsPropertyReference(ref) is true
    i. Let thisValue be GetBase(ref).
  b. Else, the base of ref is an Environment Record
    i. Let thisValue be the result of calling the ImplicitThisValue concrete method of GetBase(ref).
8. Return the result of calling the [[Call]] internal method on func, providing thisValue as the this value and
providing the list argList as the argument values

from ECMA 5.1, 11.2.3 Function Calls

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值