How to pass argument to Object prototyped with prototype?

Asked

Viewed 67 times

5

With this of to do this:

function Biscoito(sabor,marca,preco) {
    this.sabor = sabor;
    this.rodas = marca;
    this.preco = preco;
    this.mostrarAtributos = function(){
        return sabor + ", " + marca + ", " + preco;
    }
}

var maizena = new Biscoito("Leite", "Maizena", 1.20);

alert(maizena.mostrarAtributos());

That is, from to define the properties of the prototype DIRECTLY in the instance through the parameters.

But if I want to do the same building the prototype with prototype? I tried to do it and it didn’t work :(

function Biscoito(sabor, marca, preco) {}
Biscoito.prototype.sabor = sabor;
Biscoito.prototype.marca = marca;
Biscoito.prototype.preco = preco;
Biscoito.prototype.mostrarAtributos = function(){
    return sabor + ", " + marca + ", " + preco;
}

var biscoito = new Biscoito("Leite", "Maizena", 1.20);

alert(biscoito.mostrarAtributos());      

1 answer

7


In your first example, nothing is defined in the prototype. The properties and method are defined directly in the instance created when you call new Biscoito(...).

In the second example have the following problems:

  1. OK set the method mostrarAtributos on the prototype, as it can be shared across multiple instances. But the properties do not make sense to define in the prototype, because you do not want all cookies share the same values. It is only useful to define properties in the prototype if they are something like static properties.

  2. Your builder does nothing. You would need to assign the arguments passed to object properties (as you did in the first example), or to properties of Biscoito.prototype (which, as I said above, would not make much sense).

  3. In mostrarAtributos, you try to access sabor, marca and preco as variables, and they don’t exist. This is generating an error. In the first example this worked because the arguments passed to the function were captured (by closure) by the function, but this does not occur in the second example for a matter of scope.

Therefore, leave the properties in the instance, and the method in the prototype:

function Biscoito(sabor,marca,preco) {
    this.sabor = sabor;
    this.rodas = marca;
    this.preco = preco;
}
Biscoito.prototype.mostrarAtributos = function(){
    return this.sabor + ", " + this.marca + ", " + this.preco;
}

var maizena = new Biscoito("Leite", "Maizena", 1.20);

alert(maizena.mostrarAtributos());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.