0

I have created a class with a constructor and a method, I'm trying to create new instances and to use the inner function but it doesn't work, i'm new to JavaScript

I have tried to do this with getting the function outside of the class but i'm trying to do it while it's inside

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));

I want it to print the bigger price but it prints the second one

  • 3
    I can't see any code where you're calling `getHigherPrice`; can you show us what you tried? (Please [edit] the question, don't add it as a comment.) – IMSoP Jun 11 '19 at 08:30
  • sorry, at the bottom – Michael Sayapin Jun 11 '19 at 08:32
  • You can't call the function from the class name unless the function is static. – Abozanona Jun 11 '19 at 08:35
  • 1) You're looking for a `static` method. 2) You're passing instances of `Jewel` into `getHigherPrice`, but you're treating them as if they were a number. The names of the arguments and their use do not correspond. – deceze Jun 11 '19 at 08:35
  • I wouldn't put that method in the class. I'd have it as a normal function declaration that accepts two Jewel instances. – Andy Jun 11 '19 at 08:51

2 Answers2

4

You could use static method that takes two instances of Jewel class, compare their prices and returns the bigger price. You call static method on class instead of class instance.

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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

Use a static method:

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

Also change your code to deal with Jewels:

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);

And you can simplify this by simply using destructuring and 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);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79