溫故而知新:從新認識JavaScript的this

溫故而知新:從新認識JavaScript的this

thisJavaScript中的一個關鍵字,關於講解this的文章,網上資源不少。這裏記錄關於this的思考:什麼是this、爲何有thisgit

什麼是this

this是描述函數執行的記錄中的一個屬性,只能在函數內部被訪問到,會在函數執行過程當中被用到。github

看規範中定義的抽象操做Call(F, V [, argumentsList])ide

The abstract operation Call is used to call the [[Call]] internal method of a function object. The operation is called with arguments F, V, and optionally argumentsList where F is the function object, V is an ECMAScript language value that is the this value of the [[Call]], and argumentsList is the value passed to the corresponding argument of the internal method. If argumentsList is not present, a new empty List is used as its value.

執行Call操做的時候已經傳進去了this值,那再看下相關表達式Function Calls的說明:函數

...
4.Let ref be the result of evaluating memberExpr.
...
9.Return ? EvaluateCall(func, ref, arguments, tailCall).

轉到EvaluateCallthis

1.If Type(ref) is Reference, then
    a. If IsPropertyReference(ref) is true, then
        i. Let thisValue be GetThisValue(ref).
    b. Else the base of ref is an Environment Record,
        i. Let refEnv be GetBase(ref).
       ii. Let thisValue be refEnv.WithBaseObject().
2.Else Type(ref) is not Reference,
    a. Let thisValue be undefined.

看這是在描述this的值如何肯定,而EvaluateCall的入參是沒有this。這麼來看的話,能夠理解,this是函數執行時,內部過程當中的某個屬性。即開頭的結論:this是描述函數執行的記錄中的一個屬性,只能在函數內部被訪問到lua

爲何有this

爲何會有,能夠思考this的使用,解決了什麼問題?prototype

You Don't Know JS: this & Object Prototypes中這麼解釋的:設計

this提供了一種更優雅的方式來隱式「傳遞」一個對象引用,所以能夠將API設計得更加簡潔而且易於複用。code

function identify() {
  return this.name.toUpperCase();
}

function speak() {
 var greeting = "Hello, I'm " + identify.call(this);
}

var me = { name: "Kyle" };
var you = { name: "Reader" };

identify.call(me); // KYLE
identify.call(you); // READER

speak.call(me); // Hello, I'm KYLE
speak.call(you); // Hello, I'm READER

(⊙o⊙)…嘗試從這個單詞自己思考下,this應該是做爲一個代詞,那就應該是起代替或指示做用,this用於近指。那指代的是什麼呢?那就又得回到ECMAScript規範:component

The base value component is either undefined, an Object, a Boolean, a String, a Symbol, a Number, or an Environment Record. A base value component of undefined indicates that the Reference could not be resolved to a binding. The referenced name component is a String or Symbol value.

這麼來看,this指代的事物的值可能性還蠻多的。考慮下,若是undefined, an Object, a Boolean, a String, a Symbol, a Number這些值,大可以使用個標識符表示便可,不必用到this

因此,大膽猜想,this是否是指代environment record,並且仍是就近的environment record???

參考資料

  1. You Don't Know JS: this & Object Prototypes
  2. What is 「this」 keyword in JavaScript?
  3. How does the 「this」 keyword work?
  4. JavaScript深刻之從ECMAScript規範解讀this
  5. JS this
  6. this 的值究竟是什麼?一次說清楚
相關文章
相關標籤/搜索