Answer the question
In order to leave comments, you need to log in
JavaScript. Declaration of object methods - is it mandatory through a prototype?
There are two options commented out in the code. Both are functional.
Is it correct to use the second option or does it waste memory?
var Greeter = (function () {
function Greeter(message) {
this.greeting = message;
// вариант 2
// this.greet = function () {return "Hello, " + this.greeting;};
}
// вариант 1
//Greeter.prototype.greet = function () { return "Hello, " + this.greeting; };
return Greeter;
})();
var a = new Greeter('123');
Answer the question
In order to leave comments, you need to log in
Correct, but it leads to the consumption of extra memory. In option 1, each instance will have its own method (i.e., these will be different functions in memory). In option 2, the method will be one for all.
Option 1 is usually used if you want to capture variables in a closure and really create different functions. If this is not necessary, then option 2 should be used.
There is also option 3:
function sayGreet() {return "Hello, " + this.greeting;};
...
sayGreet.apply(greeter);
If you do this in a closure (for example, require), then you get a private method.
I recommend reading javascript: good parts. I recently read it on the advice of my colleagues, a lot of things fell apart in my head, although before that I wrote decently in js.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question