代码之家  ›  专栏  ›  技术社区  ›  DR01D

如何从factory函数的方法中删除'this'关键字?

  •  1
  • DR01D  · 技术社区  · 8 年前

    我的问题 在下面的简单工厂函数中,我使用 this 在totalCost方法中引用其父对象。如果不使用 这 ?我看不出该用什么图案。

    "use strict"
    
    function planeCreator(a, b, c) {
        return {
            manufacturer: a,
            numberOfEngines: b,
            costPerEngine: c,
            totalCost: function() {
                return this.numberOfEngines * this.costPerEngine;
            }
        }
    }
    
    let b17 = planeCreator('B-17', 4, 25000);
    
    document.querySelectorAll('.output')[0].textContent = b17.totalCost();
    <div class='output'></div>

    背景故事 我对Javascript读得越多,就越觉得有人批评我 Constructor 功能和 new 和 这 关键词。在里面 The Two Pillars of JavaScript Eric Elliott警告程序员不要使用构造函数,并提到Douglas Crockford从未使用 新 或 这 。

    我的问题是,虽然很容易避免构造函数和new关键字,但我不太确定如何避免 这 .我会用什么图案来代替它?

    1 回复  |  直到 8 年前
        1
  •  2
  •   CertainPerformance    8 年前

    将新创建的对象指定给变量,并引用该变量:

    (还要注意,如果只是选择单个元素,最好使用 querySelector 而不是 querySelectorAll )

    function planeCreator(a, b, c) {
      const objToReturn = {
        manufacturer: a,
        numberOfEngines: b,
        costPerEngine: c,
        totalCost: () => objToReturn.numberOfEngines * objToReturn.costPerEngine,
      };
      return objToReturn;
    }
    
    const b17 = planeCreator('B-17', 4, 25000);
    
    document.querySelector('.output').textContent = b17.totalCost();
    <div class='output'></div>

    就个人而言,我认为使用Class关键字和 this -少一些语法干扰是很好的,就像所有的语言构造一样,您只需学习如何正确使用它。你确实应该避免 这 当你不需要它,但你不应该去太多 让开 我想是为了避免使用它。同样,ES6 .reduce 对新手来说可能也很困惑,但一旦你理解了如何正确使用它,就继续使用它吧。它简洁有力。