How to pass argument to Prototype object with prototype?

5

With this 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, you can 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 this and it did not 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());      
    
asked by anonymous 21.12.2014 / 21:39

1 answer

7

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

In the second example you have the following problems:

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

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

  • In mostrarAtributos , you try to access sabor , marca and preco as variables , and they do not exist. This is generating an error. In the first example this worked because the arguments passed to the function were eventually caught (by closure ) by the function, but this does not occur in the second example as a scope.

    So, 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());
    
        
  • 21.12.2014 / 22:50