规范类型之——Reference(告诉你js是怎么获取this的)

350 阅读2分钟

数据类型有很多种:

1.语言类型:是开发者直接使用ECMAScript可以直接操作的:undefined,bull,boolean,string,number,object,simbol,blint

2.规范类型:用来描述语言类型:Reference,List,Completion,Property Descriptor,Property Identifier,Lexical EnvironmentEmvironment Record

Reference

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

翻译:Reference 类型就是用来解释诸如deletetypeof 以及赋值等操作行为的

Reference由三部分构成:

  1. base value
  2. referenced name
  3. strict reference
var foo = 1;

实际上reference是:
var fooReference = {
    base:EnvironmentRecord,
    name:'foo',
    strict:false
}

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

实际上reference是:
var BarReference = {
    base:foo,
    propertyName:'bar',
    strict:false
}

获取规范Reference组成部分的方法:

  • 1.GetBase(V):returns the base value component of the reference V(返回base value
  • 2.IsPropertyReference(V):returns true iff either the vase value is an object or HasPrimitiveBase(V) is true;otherwise return false.(如果base value是对象或者HasPrimitiveBase则返回true)
  • 3.GetValue(V): 返回具体的值,name指向的value

偷懒了,直接截图来 image.png

意思是:

1.先获取到 MemberExpression 赋值给ref,MemberExpression为:() 左边那个名字
如果 ref 是 Reference,并且 IsPropertyReference(ref) 是 true, 那么 this 的值为 GetBase(ref)

2.如果 ref 是 Reference:
    2.1通过GetBase(ref)去获取结果,如果是对象则返回
    2.2如果返回是 Environment Record, 那么this的值为 ImplicitThisValue(ref)
        2.2.1 ImplicitThisValue 方法的介绍:该函数始终返回 undefined

3.如果 ref 不是 Reference,那么 this 的值为 undefined

其他有趣文章的传送门:

image.png