There is a big difference between 2, one of the most confusing parts with prototypes is the fact that you have a prototype and a proto .
Protoype is a special property of function objects, whenever you call a constructor function with a new keyword, the proto of the instance will be the prototype of the constructor.
Object.create - , .
, Child 1 -, -, .
, , , .
, 2
, , , , .
1:
Child.prototype = Object.create(Parent.prototype);
function Parent(){
this.x = 0;
}
Parent.prototype.add = function(n){
this.x+= n;
return this.x;
};
var parentInstance = new Parent();
console.log('new Parent instance');
console.log('parentInstance.add(1): ' + parentInstance.add(1));
console.log('now letss add child, which will always add 10, to the add value');
function Child(){
Parent.call(this);
}
console.log('setting child prototype via method 1');
console.log('Child.prototype = Object.create(Parent.prototype);');
Child.prototype = Object.create(Parent.prototype);
console.log('overriding child add function, to always add 10 to given n');
Child.prototype.add = function(n){
this.x+= n + 10;
return this.x;
}
var childInstance = new Child();
console.log('new child instance');
console.log('childInstance.add(1): ' + childInstance.add(1));
console.log('yay child is working');
console.log('now lets add again to our parent instance');
console.log('parentInstance.add(1): ' + parentInstance.add(1));
console.log('yay parent is still working');
Hide result2:
Child.prototype = Parent.prototype;
function Parent(){
this.x = 0;
}
Parent.prototype.add = function(n){
this.x+= n;
return this.x;
};
var parentInstance = new Parent();
console.log('new Parent instance');
console.log('parentInstance.add(1): ' + parentInstance.add(1));
console.log('now letss add child, which will always add 10, to the add value');
function Child(){
Parent.call(this);
}
console.log('setting child prototype via method 2');
console.log('Child.prototype = Parent.prototype;');
Child.prototype = Parent.prototype;
console.log('overriding child add function, to always add 10 to given n');
Child.prototype.add = function(n){
this.x+= n + 10;
return this.x;
}
var childInstance = new Child();
console.log('new child instance');
console.log('childInstance.add(1): ' + childInstance.add(1));
console.log('yay child is working');
console.log('now lets add again to our parent instance');
console.log('parentInstance.add(1): ' + parentInstance.add(1));
console.log('oops we broke parent');
Hide result