我如何在类外部的类内部调用函数

时间:2019-06-11 08:28:16

标签: javascript

我用构造函数和方法创建了一个类,我试图创建新的实例并使用内部函数,但是它不起作用,我是JavaScript新手

我试图通过在类之外获取函数来做到这一点,但是我试图在函数位于内部时做到这一点

class Jewel {
    constructor(type, price) {
        this.type = type;
        this.price = price;
    }
    getHigherPrice(jewel1Price, jewel2Price) {
        if (jewel1Price > jewel2Price) {
            return jewel1.price;
        } else {
            return jewel2.price;
        }
    }
}
let biggerPrice = Jewel.getHigherPrice(new Jewel("bracelet", 300), new Jewel("ring", 200));

我希望它打印出更大的价格,但它会打印出第二个

2 个答案:

答案 0 :(得分:4)

您可以使用static方法,该方法接受Jewel类的两个实例,比较它们的价格并返回更大的价格。您在类而不是类实例上调用静态方法。

class Jewel {
  constructor(type, price) {
    this.type = type;
    this.price = price;
  }

  static getHigherPrice(a, b) {
    return a.price > b.price ? a.price : b.price;
  }
}
let biggerPrice = Jewel.getHigherPrice(
  new Jewel("bracelet", 300),
  new Jewel("ring", 200)
);

console.log(biggerPrice)

答案 1 :(得分:0)

使用静态方法:

static getHigherPrice(jewel1Price, jewel2Price) {...}

还要更改您的代码以处理Jewel

class Jewel {
  constructor(type, price) {
    this.type = type;
    this.price = price;
  }
  static getHigherPrice(jewel1, jewel2) {
    if (jewel1.price > jewel2.price) {
      return jewel1.price;
    } else {
      return jewel2.price;
    }
  }
}
let biggerPrice = Jewel.getHigherPrice(new Jewel("bracelet", 300), new Jewel("ring", 200));
console.log(biggerPrice);

您可以通过使用解构和Math.max来简化此操作:

class Jewel {
  constructor(type, price) {
    this.type = type;
    this.price = price;
  }
  static getHigherPrice({ price: a }, { price: b }) {
    return Math.max(a, b);
  }
}
let biggerPrice = Jewel.getHigherPrice(new Jewel("bracelet", 300), new Jewel("ring", 200));
console.log(biggerPrice);