Home > Enterprise >  Object is returning method as property when I console.log
Object is returning method as property when I console.log

Time:02-06

I have a constructor to create products and a method to check if there's stock. The problem is that when I try to console.log the product is being displayed with the method.

class Product{
    constructor(id, name, price, stock){
        this.id = id;
        this.name = name;
        this.price = price;
        this.stock = stock;
    }
    checkstock = () => this.stock > 0 ? console.log("Available stock") : console.log("No stock");
}
const product1 = new Product(001, "Keyboard", "$19.95", 3);
product1.checkstock();
console.log(product1)

The result was this:

Product { checkstock: [λ: checkstock],
  id: 1,
  name: 'Keyboard',
  price: '$19.95',
  stock: 3 }
  ​​​​​at ​​​​​​​​product1

CodePudding user response:

The problem comes from the 'checkstock' method declaration with an arrow function.

It is preferable to use a more classical syntax.

class Product{
    constructor(id, name, price, stock){
        this.id = id;
        this.name = name;
        this.price = price;
        this.stock = stock;
    }
    checkstock() {
        return this.stock > 0 ? console.log("Available stock") : console.log("No stock");
    }
}

CodePudding user response:

Methods are usually functions on the prototype. They are shared among instances.

But your "method" is indeed an instance's own property. It is not on the prototype and therefore not shared among other instances.

To define methods, use the syntax for method definitions:

class {
  method() {}
}
  • Related