【问题标题】:Inside an object is it possible for a method to use the return value of another method?在对象内部,一个方法可以使用另一个方法的返回值吗?
【发布时间】:2018-10-01 16:54:26
【问题描述】:

在下面的测试代码中,工厂函数创建了一个对象。新对象内部有 2 个方法,totalCostwithShipping。有没有我可以使用的模式允许withShipping 使用totalCost 的返回值?按照配置,它会引发错误。非常感谢您的帮助!

"use strict"

function factoryTest(x) {
    let returnTest = {
        numberOfEngines: x.numberOfEngines,
        costPerEngine: x.costPerEngine,
        totalCost: function() {
            return x.numberOfEngines * x.costPerEngine;
        },
        withShipping: function() {
            return x.totalCost() * 2;
        }

    }
    return returnTest;
}

let aircraft = factoryTest({numberOfEngines: 2, costPerEngine: 40000});

console.log(aircraft.totalCost());
console.log(aircraft.withShipping());

【问题讨论】:

    标签: javascript methods javascript-objects


    【解决方案1】:

    最简单的方法是使用this 访问当前实例化:

    "use strict"
    
    function factoryTest(x) {
        let returnTest = {
            numberOfEngines: x.numberOfEngines,
            costPerEngine: x.costPerEngine,
            totalCost: function() {
                return x.numberOfEngines * x.costPerEngine;
            },
            withShipping: function() {
                return this.totalCost() * 2;
            }
    
        }
        return returnTest;
    }
    
    let aircraft = factoryTest({numberOfEngines: 2, costPerEngine: 40000});
    
    console.log(aircraft.totalCost());
    console.log(aircraft.withShipping());

    由于您使用的是工厂函数模式,另一种可行的方法是定义totalCost 函数以及returnTest 之外的所有其他 函数,然后调用它:

    "use strict"
    
    function factoryTest({
      numberOfEngines,
      costPerEngine
    }) {
      const totalCost = () => numberOfEngines * costPerEngine;
      return {
        numberOfEngines,
        costPerEngine,
        totalCost,
        withShipping: () => totalCost() * 2,
      };
    }
    
    const aircraft = factoryTest({
      numberOfEngines: 2,
      costPerEngine: 40000
    });
    
    console.log(aircraft.totalCost());
    console.log(aircraft.withShipping());

    【讨论】:

    • 你是对的!一个问题xthis 不是引用同一个对象吗?为什么this 工作而x 失败?它们看起来很相似。
    • x 实际上是指{numberOfEngines: 2, costPerEngine: 40000} 对象,注意它上面没有定义“totalCost”吗?所有x 都是“numberOfEngines”和“costPerEngine”
    猜你喜欢
    • 2018-09-18
    • 2016-12-27
    • 2017-10-01
    • 2016-05-13
    • 2020-12-11
    • 2011-09-27
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多