Answer the question
In order to leave comments, you need to log in
What is the fundamental difference in defining methods for an object prototype in JS for the two options?
There are two options for defining a constructor function and its prototype methods.
What is their fundamental difference? How correct is option 2? Can there be any pitfalls in doing so?
// Variant 1
function Obj(prop1, prop2) {
this.p1 = prop1;
this.p2 = prop2;
}
Obj.prototype.greet = function() {
alert(this.p1);
}
Obj.prototype.getP2 = function() {
return this.p2;
}
// Variant 2
function Obj(prop1, prop2) {
this.p1 = prop1;
this.p2 = prop2;
}
Obj.prototype = {
greet : function() {
alert(this.p1);
},
getP2 : function() {
return this.p2;
}
}
Answer the question
In order to leave comments, you need to log in
I show clearly:
function q(){}
q.prototype.w = 2;
console.log(new q().w); // 2
q.prototype = {
e : 3
}
console.log(new q().w); // undefined
console.log(new q().e); // 3
The first option is “correct” (although it depends on preferences sometimes :))
In the first case, all objects created with this constructor will share the prototype and it is worth changing it in one place and it will change for all called objects. In the second option, you create a function for each object separately.
The second option is sometimes NEEDED to be used according to the requirements of the algorithm itself, such as complex inheritance chains (inheritance)
I think I explained everything clearly. There may be errors in terminology. I got an education and I work not in Russian :)
When you create a function, it has a prototype property, which is an "empty" object. In fact, instances will inherit from Object. When you assign prototype to another object, the instances will inherit from its prototype. In your example, you are assigning an anonymous object that inherits from Object. Thus, for your example, there is no fundamental difference . For the most part, as you like, or as it is more convenient in a certain situation.
I would not say that there are some pitfalls here if you understand how objects are arranged in js. A lot depends on what you want to achieve. For example, if you assign the same object to the prototypes of different classes, then they will have, as it were, one prototype - that is, properties are not copied / added, but the usual assignment occurs.
But if you assign an anonymous object to the prototype, then most likely there will be no problems.
It is also worth remembering that assigning another object to prototype is used for inheritance.
There are quite a lot of materials about inheritance and about javascript in general on Habré (for example, searching for “javascript prototype inheritance” yields many interesting articles). Get to know them.
When you understand how prototype works, you won't have these questions.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question