this
是JavaScript
中的一個關鍵字,關於講解this
的文章,網上資源不少。這裏記錄關於this
的思考:什麼是this
、爲何有this
。git
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).
轉到EvaluateCall:this
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
設計得更加簡潔而且易於複用。codefunction 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
???