this

原文出處

JavaScript深入之從ECMAScript規(guī)范解讀this
ECMA-262-3 in detail. Chapter 3. This
ECMAScript5.1中文版
ECMAScript5.1英文版

Types


首先是第 8 章 Types:

Types are further subclassified into ECMAScript language types and specification types.

An ECMAScript language type corresponds to values that are directly manipulated by an ECMAScript programmer using the ECMAScript language. The ECMAScript language types are Undefined, Null, Boolean, String, Number, and Object.

A specification type corresponds to meta-values that are used within algorithms to describe the semantics of ECMAScript language constructs and ECMAScript language types. The specification types are Reference, List, Completion, Property Descriptor, Property Identifier, Lexical Environment, and Environment Record.

我們簡單的翻譯一下:

ECMAScript 的類型分為語言類型和規(guī)范類型。

ECMAScript 語言類型是開發(fā)者直接使用 ECMAScript 可以操作的。其實(shí)就是我們常說的Undefined, Null, Boolean, String, Number, 和 Object。

而規(guī)范類型相當(dāng)于 meta-values,是用來用算法描述 ECMAScript 語言結(jié)構(gòu)和 ECMAScript 語言類型的。規(guī)范類型包括:Reference, List, Completion, Property Descriptor, Property Identifier, Lexical Environment, 和 Environment Record。

沒懂?沒關(guān)系,我們只要知道在 ECMAScript 規(guī)范中還有一種只存在于規(guī)范中的類型,它們的作用是用來描述語言底層行為邏輯

Reference


那什么又是 Reference ?

讓我們看 8.7 章 The Reference Specification Type

The Reference type is used to explain the behaviour of such operators as delete, typeof, and the assignment operators.

所以 Reference 類型就是用來解釋諸如 delete、typeof 以及賦值等操作行為的。

抄襲尤雨溪大大的話,就是:

這里的 Reference 是一個 Specification Type,也就是 “只存在于規(guī)范里的抽象類型”。它們是為了更好地描述語言的底層行為邏輯才存在的,但并不存在于實(shí)際的 js 代碼中。

再看接下來的這段具體介紹 Reference 的內(nèi)容:

A Reference is a resolved name binding.

A Reference consists of three components, the base value, the referenced name and the Boolean valued strict reference flag.

The base value is either undefined, an Object, a Boolean, a String, a Number, or an environment record (10.2.1).

A base value of undefined indicates that the reference could not be resolved to a binding. The referenced name is a String.

這段講述了 Reference 的構(gòu)成,由三個組成部分,分別是:

  1. base value: 就是屬性所在的對象或者就是 EnvironmentRecord,它的值只可能是 undefined, an Object, a Boolean, a String。

  2. referenced name: 就是屬性的名稱。

  3. strict reference: 是否處于嚴(yán)格模式。

舉個例子:

var foo = 1;

// 對應(yīng)的Reference是:
var fooReference = {
    base: EnvironmentRecord,
    name: 'foo',
    strict: false
};

再舉個例子:

var foo = {
    bar: function () {
        return this;
    }
};
 
foo.bar(); // foo

// bar對應(yīng)的Reference是:
var BarReference = {
    base: foo,
    propertyName: 'bar',
    strict: false
};

而且規(guī)范中還提供了獲取 Reference 組成部分的方法,比如 GetBase 和 IsPropertyReference
這兩個方法很簡單,簡單看一看:

1.GetBase

GetBase(V). Returns the base value component of the reference V.

返回 reference 的 base value。

  1. IsPropertyReference

IsPropertyReference(V). Returns true if either the base value is an object or HasPrimitiveBase(V) is true; otherwise returns false.

簡單的理解:如果 base value 是一個對象,就返回true。

GetValue


除此之外,緊接著在8.7.1 章規(guī)范中就講了一個用于從 Reference 類型獲取對應(yīng)值的方法: GetValue

簡單模擬 GetValue 的使用:

var foo = 1;

var fooReference = {
    base: EnvironmentRecord,
    name: 'foo',
    strict: false
};

GetValue(fooReference) // 1;

GetValue 返回對象屬性真正的值,但是要注意:
調(diào)用 GetValue,返回的將是具體的值,而不再是一個 Reference

如何確定this的值


規(guī)范 11.2.3 Function Calls

這里講了當(dāng)函數(shù)調(diào)用的時候,如何確定 this 的取值。
只看第一步、第六步、第七步:

1.Let ref be the result of evaluating MemberExpression.

6.If Type(ref) is Reference, then

    a.If IsPropertyReference(ref) is true, then
            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).

7.Else, Type(ref) is not Reference.

   a. Let thisValue be undefined.

讓我們描述一下:

  1. 計(jì)算 MemberExpression 的結(jié)果賦值給 ref

  2. 判斷 ref 是不是一個 Reference 類型

     2.1 如果 ref 是 Reference,并且 IsPropertyReference(ref) 是 true, 那么 this 的值為 GetBase(ref)
     2.2 如果 ref 是 Reference,并且 base value 值是 Environment Record, 那么this的值為 ImplicitThisValue(ref)
     2.3 如果 ref 不是 Reference,那么 this 的值為 undefined
    

具體分析


讓我們一步一步看:

  1. 計(jì)算 MemberExpression 的結(jié)果賦值給 ref

什么是 MemberExpression?看規(guī)范 11.2 Left-Hand-Side Expressions

MemberExpression :

  • PrimaryExpression // 原始表達(dá)式 可以參見《JavaScript權(quán)威指南第四章》
  • FunctionExpression // 函數(shù)定義表達(dá)式
  • MemberExpression [ Expression ] // 屬性訪問表達(dá)式
  • MemberExpression . IdentifierName // 屬性訪問表達(dá)式
  • new MemberExpression Arguments // 對象創(chuàng)建表達(dá)式

舉個例子:

function foo() {
    console.log(this)
}

foo(); // MemberExpression 是 foo

function foo() {
    return function() {
        console.log(this)
    }
}

foo()(); // MemberExpression 是 foo()

var foo = {
    bar: function () {
        return this;
    }
}

foo.bar(); // MemberExpression 是 foo.bar

所以簡單理解 MemberExpression 其實(shí)就是()左邊的部分

2.判斷 ref 是不是一個 Reference 類型。

關(guān)鍵就在于看規(guī)范是如何處理各種 MemberExpression,返回的結(jié)果是不是一個Reference類型。

舉最后一個例子:

var value = 1;

var foo = {
  value: 2,
  bar: function () {
    return this.value;
  }
}

//示例1
console.log(foo.bar());
//示例2
console.log((foo.bar)());
//示例3
console.log((foo.bar = foo.bar)());
//示例4
console.log((false || foo.bar)());
//示例5
console.log((foo.bar, foo.bar)());

foo.bar()

在示例 1 中,MemberExpression 計(jì)算的結(jié)果是 foo.bar,那么 foo.bar 是不是一個 Reference 呢?

查看規(guī)范 11.2.1 Property Accessors,這里展示了一個計(jì)算的過程,什么都不管了,就看最后一步:

Return a value of type Reference whose base value is baseValue and whose referenced name is propertyNameString, and whose strict mode flag is strict.

我們得知該表達(dá)式返回了一個 Reference 類型!
根據(jù)之前的內(nèi)容,我們知道該值為:

var Reference = {
  base: foo,
  name: 'bar',
  strict: false
};

接下來按照 2.1 的判斷流程走:

2.1 如果 ref 是 Reference,并且 IsPropertyReference(ref) 是 true, 那么 this 的值為 GetBase(ref)

該值是 Reference 類型,那么 IsPropertyReference(ref) 的結(jié)果是多少呢?

前面我們已經(jīng)鋪墊了 IsPropertyReference 方法,如果 base value 是一個對象,結(jié)果返回 true。

base value 為 foo,是一個對象,所以 IsPropertyReference(ref) 結(jié)果為 true。

這個時候我們就可以確定 this 的值了:

this = GetBase(ref)

GetBase 也已經(jīng)鋪墊了,獲得 base value 值,這個例子中就是foo,所以 this 的值就是 foo ,示例1的結(jié)果就是 2!

(foo.bar)()

看示例2:

console.log((foo.bar)());

foo.bar 被 () 包住,查看規(guī)范 11.1.6 The Grouping Operator
直接看結(jié)果部分:

Return the result of evaluating Expression. This may be of type Reference.

NOTE This algorithm does not apply GetValue to the result of evaluating Expression.

實(shí)際上 () 并沒有對 MemberExpression 進(jìn)行計(jì)算,所以其實(shí)跟示例 1 的結(jié)果是一樣的。

(foo.bar = foo.bar)()

看示例3,有賦值操作符,查看規(guī)范11.13.1 Simple Assignment ( = ):

3.Let rval be GetValue(rref).

因?yàn)槭褂昧?GetValue,所以返回的值不是 Reference 類型

按照之前講的判斷邏輯:

2.3 如果 ref 不是Reference,那么 this 的值為 undefined

this 為 undefined,非嚴(yán)格模式下,this 的值為 undefined 的時候,其值會被隱式轉(zhuǎn)換為全局對象。

(false || foo.bar)()

看示例4,邏輯與算法,查看規(guī)范 11.11 Binary Logical Operators
計(jì)算第二步:

2.Let lval be GetValue(lref).

因?yàn)槭褂昧?GetValue,所以返回的不是 Reference 類型,this 為 undefined

(foo.bar, foo.bar)()

看示例5,逗號操作符,查看規(guī)范11.14 Comma Operator ( , )

計(jì)算第二步:

2.Call GetValue(lref).

因?yàn)槭褂昧?GetValue,所以返回的不是 Reference 類型,this 為 undefined

揭曉結(jié)果

所以最后一個例子的結(jié)果是:

var value = 1;

var foo = {
  value: 2,
  bar: function () {
    return this.value;
  }
}

//示例1
console.log(foo.bar()); // 2
//示例2
console.log((foo.bar)()); // 2
//示例3
console.log((foo.bar = foo.bar)()); // 1
//示例4
console.log((false || foo.bar)()); // 1
//示例5
console.log((foo.bar, foo.bar)()); // 1

注意:以上是在非嚴(yán)格模式下的結(jié)果,嚴(yán)格模式下因?yàn)?this 返回 undefined,所以示例 3 會報(bào)錯。

補(bǔ)充

最最后,忘記了一個最最普通的情況:

function foo() {
    console.log(this)
}

foo(); 

MemberExpression 是 foo,解析標(biāo)識符,查看規(guī)范 10.3.1 Identifier Resolution,會返回一個 Reference 類型的值:

var fooReference = {
    base: EnvironmentRecord,
    name: 'foo',
    strict: false
};

接下來進(jìn)行判斷:

2.1 如果 ref 是 Reference,并且 IsPropertyReference(ref) 是 true, 那么 this 的值為 GetBase(ref)

因?yàn)?base value 是 EnvironmentRecord,并不是一個 Object 類型,還記得前面講過的 base value 的取值可能嗎? 只可能是 undefined, an Object, a Boolean, a String, a Number, 和 an environment record 中的一種。

IsPropertyReference(ref) 的結(jié)果為 false,進(jìn)入下個判斷:

2.2 如果 ref 是 Reference,并且 base value 值是 Environment Record, 那么this的值為 ImplicitThisValue(ref)

base value 正是 Environment Record,所以會調(diào)用 ImplicitThisValue(ref)

查看規(guī)范 10.2.1.1.6,ImplicitThisValue 方法的介紹:該函數(shù)始終返回 undefined。

所以最后 this 的值就是 undefined。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容