【问题标题】:What's the difference between two set of codes, I know what arrow function does but why traditional expression does not work?两组代码有什么区别,我知道箭头函数是做什么的,但为什么传统的表达方式不起作用?
【发布时间】:2022-01-08 16:43:23
【问题描述】:

两组代码有什么区别,我知道箭头函数是做什么的,但是为什么传统的表达方式不行?

设置 - 1

循环遍历所有元素

    checkboxes.forEach( function (checkbox){
        console.log(checkbox);

        if( checkbox === this || checkbox === lastChecked)
        {
            inBetween = !inBetween;
            console.log(" start checking them inbetween");

        }

        if(inBetween)
        {
            checkbox.checked = true;
        }
    });

设置 - 2

循环遍历所有元素

  checkboxes.forEach(checkbox => {

  console.log(checkbox);
  if (checkbox === this || checkbox === lastChecked) {
    inBetween = !inBetween;
    console.log('Starting to check them in between!');
  }

  if (inBetween) {
    checkbox.checked = true;
  }
});

【问题讨论】:

    标签: javascript web


    【解决方案1】:

    我认为,可能你在forEach()函数的范围内使用this,这是两个不同的一个。
    更多解释是:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

    【讨论】:

    • 是的,我认为是这样,因为这取决于函数的调用方式,或者必须使用 bind 方法以及它来设置函数 this 的值,而不管它是如何调用的
    【解决方案2】:

    Set-1 是 ES5 定义风格的 foreach,而 Set-2 是 ES6 的。确保目标/版本支持 ES5,这样 Set-1 才能工作。

    另外,您可能想尝试在 set-1 中将 this 替换为 self 并在 foreach 之前将 self 定义为 this 或使用 bind

      var self = this;
    this.addNewObjects = function(arr){
        arr.forEach(function(obj) {
            self.addObject(new Obj(obj.prop1, obj.prop2));
        });
    }
    

        this.addNewObjects = function(arr) {
        arr.forEach(function(obj) {
            this.addObject(new Obj(obj.prop1, obj.prop2));
        }.bind(this));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 2020-09-19
      • 2014-01-17
      • 2016-09-26
      • 2021-11-07
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多