【问题标题】:Assign function return value to value in Javascript function [closed]将函数返回值分配给Javascript函数中的值[关闭]
【发布时间】:2018-01-19 01:03:16
【问题描述】:

这是我遇到的问题的简化示例。

function Part(price, qty) {
  this.price = price;
  this.qty = qty;
  this.value = function() {
    return this.price * this.qty
  }
}

var fancyPart = new Part(2, 3);


console.log(fancyPart.value)

我希望将6 打印到控制台,而不是打印:

function () {
    return this.price * this.qty
  }

为什么会这样?

我正在尝试使用它来创建一个“对象”,并且正在阅读关于这个问题的各种方法:Which way is best for creating an object in javascript? is "var" necessary before variable of object?

【问题讨论】:

  • console.log(fancyPart.value()) — 你必须调用函数。
  • @Pointy...谢谢。这太明显了。
  • 或者您可以将 value 实现为 getter。 ;-)

标签: javascript function


【解决方案1】:

您可以使用类语法并添加 value 作为 getter:

class Part {
  constructor (price, qty) {
    this.price = price;
    this.qty = qty;
  };

  // Implement value as a getter
  get value() {
    return this.price * this.qty
  };

}

var fancyPart = new Part(2, 3);

// No need for parameter list
console.log(fancyPart.value)

【讨论】:

  • 谢谢。这就是我想要做的——只是使用了不正确的术语。
【解决方案2】:

尝试console.log(fancyPart.value())... 调用(调用)函数

function Part(price, qty) {
  this.price = price;
  this.qty = qty;
  this.value = function() {
    return this.price * this.qty
  }
}

var fancyPart = new Part(2, 3);


console.log(fancyPart.value())

【讨论】:

    【解决方案3】:

    您可以从您的构造函数中将该值作为函数分配

    this.value = function() { 返回 this.price * this.qty }

    因此,当您尝试记录 fancyPart.value 时,您实际上是在记录函数而不是调用。

    如果你在 value 后面加上“()”,你实际上会调用函数并得到你期望的评估(即 6 在 fancypants.value 的情况下)

    【讨论】:

      【解决方案4】:

      或者你可以与众不同,使用Function.prototype.call

      function Part(price, qty) {
        this.price = price;
        this.qty = qty;
        this.value = function() {
          return this.price * this.qty
        }
      }
      
      var fancyPart = new Part(2, 3);
      
      
      console.log(fancyPart.value.call(fancyPart))

      【讨论】:

        猜你喜欢
        • 2021-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-06
        • 2012-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多