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
???