Js prototype inherited development
when learning js prototype inheritance development, I found two prototyping methods. What is the difference?
function Dialog(){}
Dialog.prototype.fun1 = function(){
console.log("fun1");
}
Dialog.prototype.fun2 = function(){
console.log("fun2");
}
---------------------------------------------
Dialog.prototype = {
constructor: this,
fun1:function(){
console.log("fun1");
},
fun2:function(){
console.log("fun2");
}
}
Is that the question you want to ask
?
when implementing inheritance through a prototype chain, you cannot use object literals to create a prototype method, as this will override the prototype chain
function SuperType() {
this.property = true;
}
SuperType.prototype.getSuperValue = function () {
return this.property;
}
function SubType() {
this.subproperty = false;
}
//SuperType
SubType.prototype = new SuperType();
//
SubType.prototype = {
getSubValue: function () {
return this.subproperty;
},
someOtherMethod: function () {
return false;
}
}
var instance = new SubType();
alert(instance.getSuperValue()); //error
if it is linked to inheritance, it is usually written in the second way, and constructer should refer back to the instance. There is also a point that combinatorial inheritance is often applied to the second way.
The
prototype itself is an object, and Dialog.prototype points to this object, the first way is equivalent to modifying the properties of the object, and the second way is equivalent to letting prototype point to an object again.
the first method does not invalidate the attributes you have added to the prototype elsewhere.
the second way should be used with caution, because you can first modify the prototype, in the first way and then overwrite it in the second way, and the things you previously added to the prototype will be gone.
var obj = {
fun1:function(){
console.log("fun1");
},
fun2:function(){
console.log("fun2");
},
};
the only difference in terms of the code you send is that the following constructor
can be enumerated
ps: your second constructor
with this
has a problem