1
1
1thater2020-04-20 10:52:29
JavaScript
1thater, 2020-04-20 10:52:29

What is the difference between a prototype method (static method) and a constructor function method?

var Juice = function (price) {
        this.price = price;
        
        this.apple = function ( ) {               // метод объекта
                console.log("Hi I'm apple juice.");
        };
};

Juice.prototype.banana = function ( ) {          // метод прототипа Juice
        console.log("Hi I'm banana juice");
};

Juice.orange = function ( ) {                 // метод функции-конструктора (некоторые называют статический метод)
        console.log("Hi I'm orange juice."); 
};

    
var littleJuice = new Juice(100);
var littleJuice = new Juice(100);
var littleJuice = new Juice(100);


When we create objects littleJuice, the price and methods of apple are laid in them, memory is allocated for all this.

When we created the method banana, it was registered once in the Juice prototype, a memory space was allocated for it 1 time, and it "does not multiply" anymore.

What to do with orange? What is a constructor method, what is it for?
Does it "reproduce" with objects or not? If not, then why are prototypes needed if the problem of "reproduction" can be solved by constructor methods or not))?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Somewhere Intech, 2020-04-20
@1thater

Thus, you have made a static function orange (public static orange), which can only be called as Juice.orange() and from this function you do not have access to the instance, of course, in your language "does not multiply with objects".

function Juice(kind, price){
   let kind = kind; // это будет приватным свойством
   this.price = price; // публичное свойство
   this.kind = () => kind; //это публичный метод
   this.hello = function(){
      console.log(`Thats ${kind} juice`)
   }
}
Juice.prototype.world = function(){
   //приватное свойство kind тут не доступно, потому обратимся к публичному методу
   console.log(`Juice kind: ${this.kind()}`)
}
// шаблон "фабрика"
Juice.apple = ( price ) => new Juice('apple', price);
Juice.orange = ( price ) => new Juice('orange', price);

let littleAppleJuice = Juice.apple(100),
   hugeBananaJuice = new Juice('banana', 500);
littleAppleJuice.hello();
littleBananaJuice.world();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question