Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

语法糖解析系列之——箭头函数 #15

Open
MyPrototypeWhat opened this issue Dec 25, 2021 · 0 comments
Open

语法糖解析系列之——箭头函数 #15

MyPrototypeWhat opened this issue Dec 25, 2021 · 0 comments

Comments

@MyPrototypeWhat
Copy link
Owner

箭头函数

const a=()=>{
	console.log(this)
}

const obj={
 a:1,
	fn(){
     const arrow=()=>{
     	console.log(this.a)
     }
    }
  
}
obj.fn() // 1

转义后(spec:true):

"use strict";

var _this = void 0;

function _newArrowCheck(innerThis, boundThis) {
  if (innerThis !== boundThis) {
    throw new TypeError("Cannot instantiate an arrow function");
  }
}

var a = function a() {
  // 检查this,也就是为什么箭头函数不能new
  _newArrowCheck(this, _this);

  console.log(this);
}.bind(void 0);

var obj = {
  a: 1,
  fn: function fn() {
    var _this2 = this;

    var arrow = function arrow() {
      _newArrowCheck(this, _this2);

      console.log(this.a);
    }.bind(this);
  }
};
obj.fn(); // 1
  • 箭头函数会被编译成 var xx=function xx(){} 形式,同时在函数外层创建_this并在函数内使用;无法变量提升。
  • 箭头函数内部会有_newArrowCheck检查是this是否相同,被new时报错。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant