【发布时间】:2018-10-19 20:05:46
【问题描述】:
谁能帮我理解下面这个小 es6 程序的输出?
我知道箭头函数和普通函数的区别。
箭头函数在父级范围内运行。 Normal 函数在自己的范围内运行。
PFB 让我困惑的程序。
function Temp(){
this.x =99;
y =88;
var z =77;
setTimeout(function(){console.log(this.y+"::",this.x,"--",this.z),5});
setTimeout(()=>{console.log(this.y+"||",this.x,"--",this.z),5});
doit(function (){ console.log(this.y+":",this.x,"_",this.z);})
doit(()=>{console.log(this.y+"|",this.x,"-",this.z);});
function doit(task){
this.i =0;
task();
}
}
new Temp();
输出
88:: undefined --undefined
undefined|| 99 --undefined
88: undefined -undefined
undefined| 99-undefined
es6 游乐场
es6console link 想知道变量声明和函数之间的关联(箭头/法线)。
【问题讨论】:
-
那么到底是什么问题:)
-
尝试严格模式(你总是应该使用的),
y =88会抛出相应的错误。以及访问未定义this上的属性。
标签: javascript ecmascript-6 arrow-functions