Home > Net >  Changing class constructor multiple properties with a single method JS
Changing class constructor multiple properties with a single method JS

Time:07-30

There is a similar question with this from almost 8 years ago but it doesn't have a clear answer for me.

I have a shopping cart constructor that it's like this:

class Carrinho {
    constructor(itens, quantidade, valorTotal) {
    this.itens = itens
    this.quantidade = quantidade
    this.valorTotal = valorTotal
    }

I want a Method to add item type and it's quantity to the resulting object. I thought on:

    addItem = function(itens, quantidade) {
    this.itens  = itens
    this.quantidade  = quantidade

This doesn't work though. Nor does 2 return lines. I've tried with object notation too {} but I wasn't successful. I also saw a similar way using for (var itens in constructor) this.itens = itens and it also didn't work.

What are the ways to do those? Or should I add multiple methods for ervery property?

CodePudding user response:

class Carrinho {
    constructor(itens, quantidade) {
    this.itens = itens;
    this.quantidade = quantidade;

    }
addItem = function(itens, quantidade) {
    this.itens  = ","   itens;
    this.quantidade  = quantidade;
}
valorTotal = function () {
return this.itens.split(',')   " = total = "   this.quantidade;
}
}
var c = new Carrinho("blue",1);
c.addItem("red", 1)
console.log(c.valorTotal());

soory i have edit the méthod

CodePudding user response:

Since addItem isn't a method of the class, it doesn't receive the object as this. You need to pass the instance as an explicit argument.

function addItem(carrinho, itens, quantidade) {
    carrinho.itens  = itens;
    carrinho.quantidade  = quantidade;
}

c = new Carrinho(1, 2, 3);
addItem(c, 5, 10)
console.log(c)
  • Related