【问题标题】:code snippet and Behaviour of Arrow function and Normal function [duplicate]箭头函数和普通函数的代码片段和行为[重复]
【发布时间】: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


【解决方案1】:

如果您没有声明变量(例如,不使用 this.y 或 constletvar 之一),它会附加到全局范围(对于 window 的浏览器)。

当您调用匿名函数时,它使用全局范围 (window)。

我在您的代码中添加了 cmets。

function Temp() {
  this.x = 99; // local scope
  y = 88; // global scope (attached on window as it is not declared)
  // this.y is never

  setTimeout(function() { // Scope is window/global
    console.log('log1', this.y + ":::", this.x)
  }, 5);

  setTimeout(() => { // Scope is Temp
    console.log('log2', this.y + "||", this.x)
  }, 5);

  doit(function() { // Because it is an anonymous function
                    // the scope is now that of window
    console.log('log3', this.y + ":", this.x);
  })
  doit(() => { // Arrow function: the scope of Temp
    console.log('log4', this.y + "|", this.x);
  });

  function doit(task) {
    this.i = 0;
    task();
  }
}

new Temp();

回顾一下:始终使用constlet 声明变量。同样为了更好地理解,请使用新的class 语法。它只是一种语法糖,但仍然有助于使您的代码更易于理解。

【讨论】:

  • 对问题进行了小修改,您可以再看看吗。您对“y”的声明所做的 cmets 真的很有帮助。尽管有人怀疑“y”是否在全局范围内声明,那么它应该由箭头函数访问。不应该吗?
猜你喜欢
  • 2019-01-17
  • 2020-05-07
  • 2015-11-03
  • 2020-02-20
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
相关资源
最近更新 更多