You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

对象内部方法能否调用其他方法返回值?工厂函数代码问题求助

当然可以!对象方法间的调用其实很简单

首先明确说:对象内部的方法完全可以使用另一个方法的返回值,你当前的问题主要是没正确引用到totalCost方法,还有原代码漏掉了返回对象的步骤~

我给你两种常见的解决方案,都能让withShipping顺利拿到totalCost的返回值:

方案1:用this引用当前对象

在对象的方法里,this默认指向当前的对象实例,所以直接用this.totalCost()就能调用另一个方法:

"use strict"
function factoryTest(x) {
  let returnTest = {
    numberOfEngines: x.numberOfEngines,
    costPerEngine: x.costPerEngine,
    totalCost: function() {
      // 这里改成用this,让方法更依赖对象自身属性,而非外部的x
      return this.numberOfEngines * this.costPerEngine;
    },
    withShipping: function(shippingCost) {
      // 通过this调用totalCost方法,拿到返回值后加上运费
      return this.totalCost() + shippingCost;
    }
  };
  // 别忘了返回创建好的对象!原代码漏掉了这一步
  return returnTest;
}

// 测试示例
const order = factoryTest({ numberOfEngines: 2, costPerEngine: 1000 });
console.log(order.totalCost()); // 输出2000
console.log(order.withShipping(200)); // 输出2200

这种方式是JavaScript面向对象的常规写法,只要你不会把withShipping方法单独从对象上拆下来调用(比如用变量保存后单独执行),this的指向就不会出问题。

方案2:利用闭包直接引用对象变量

因为在工厂函数内部我们已经有了returnTest这个对象变量,所以可以直接在withShipping里用它来调用totalCost,这种方式能避免this绑定的潜在问题:

"use strict"
function factoryTest(x) {
  let returnTest = {
    numberOfEngines: x.numberOfEngines,
    costPerEngine: x.costPerEngine,
    totalCost: function() {
      return x.numberOfEngines * x.costPerEngine;
    },
    withShipping: function(shippingCost) {
      // 直接用工厂函数里的returnTest变量调用方法
      return returnTest.totalCost() + shippingCost;
    }
  };
  return returnTest;
}

这种方式的优势在于,哪怕你把withShipping方法单独提取出来执行(比如const ship = order.withShipping; ship(200)),它依然能正确调用totalCost——因为returnTest是工厂函数内部的变量,形成了闭包。

另外要提醒你:原代码里忘记了return returnTest,这会导致调用factoryTest后拿不到创建的对象,这也是可能触发错误的原因之一哦!


内容的提问来源于stack exchange,提问作者DR01D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:33:39