【问题标题】:Meteor - Arrow Functions breaking #each loop in ES6 [duplicate]Meteor - 箭头函数打破 ES6 中的 #each 循环 [重复]
【发布时间】:2016-06-13 16:22:24
【问题描述】:

我希望我有合适的区域来要求这个... 下面是我正在处理的两个文件中的一些代码。当我将函数中带有“this.”的任何内容更改为箭头函数时,代码不再按预期运行。

有人能够解释我做错了什么吗?使用箭头函数时我需要做一些不同的事情吗?我在用“这个”吗?开始不正确?我不应该以这种方式使用箭头函数吗?

非常感谢您的帮助。

client/views/jobList.html

{{#each jobs}}
    <tr>
        <td>{{jobID}}</td>
            <td>{{user.fullname}}</td>
            <td>{{product.type}}</td>
            <td>{{shortDesc}}</td>
            <td>{{formattedDate}}</td>
            <td>{{phone}}</td>
            <td>{{user.username}}</td>
            <td>{{jobType}}</td>
            <td>{{product.brand}}</td>
            <td>{{product.type}}</td>
            <td>{{product.model}}</td>
        </tr>
    {{/each}}

client/views/jobList.js

Template.jobList.helpers({
    jobs: ()=> Jobs.find({}, {sort: {jobDate: 1}}),

    formattedDate: function() { // Changing this to arrow function breaks functionality
        let d = this.jobDate;
        let e = formatDate(d);
        return e;
    },
    shortDesc: function () { // Changing this to arrow function breaks functionality
        if (this.description.length > 40) {
            return this.description.substr(0, 50) + '...';
        } else {
            return this.description
        }
    },
    jobID: function () { // Changing this to arrow function breaks functionality
        let a = this.jobNum;
        let e = this.jobType.substr(0, 1);
        return e + a
    }
});

【问题讨论】:

  • 请向我们展示您的箭头功能不起作用?我们告诉您它是否正确的最佳方式;)
  • 如果我将帮助程序中包含this 的任何方法更改为箭头函数......在中编辑

标签: javascript meteor ecmascript-6 meteor-blaze


【解决方案1】:

箭头函数的一个基本特性是它们在创建它们的上下文中继承(关闭this。您的代码依赖于函数调用方式设置的this,因此箭头函数不是一个好的选择。

以下是差异和问题的说明:

var obj = {
    foo: () => {
        console.log("foo: this.prop:", this.prop);
    },
    bar: function() {
        console.log("bar: this.prop:", this.prop);
    },
    prop: "the property"
};
obj.foo(); // Doesn't show `prop` because `this` != `obj`
obj.bar(); // Does show `prop` because `this` == `obj`

【讨论】:

  • 好吧,这就是我开始思考的方向。那么,在这些情况下,我应该只使用标准函数声明吗?
  • 谢谢!非常感谢:)
  • @jERCle:这些不是函数声明(它们是函数表达式),但是是的,使用标准(非箭头)函数。如果您愿意,可以通过在对象初始化器中使用方法语法(这是 ES2015 中的另一个新事物)使它们更简洁:pastie.org/10874562.
  • 哦,是的,我的错。对此还是陌生的。谢谢,我根本没想过使用那种语法。
  • @jERCle:嘿,它是全新的,没想到它并不奇怪。 :-)
猜你喜欢
  • 2016-03-25
  • 2016-08-06
  • 2018-08-01
  • 2018-08-02
  • 2018-07-18
  • 2018-02-11
  • 2016-12-08
  • 1970-01-01
相关资源
最近更新 更多