i want to learn how to use prototype in javascript, i learn that prototype can help me for example sharing functions between many objects
var car = function(color, speed) {
this.color = color;
this.speed = speed;
}
car.prototype.doors = 4;
var honda = new car('black', 'beep');
var kea = new car('black', 'meep');
document.write(kea.doors+' '+ honda.doors);
honda.doors = 2;
document.write('<br/>');
document.write(kea.doors+' '+ honda.doors);
car.prototype.doors = 4;
document.write('<br/>');
document.write(kea.doors+' '+ honda.doors);
I saw a video here : Here
The guy said that if i update the value of the prototype then the variable will change in all my objectsbut here in my example the value did not change when i changed it. Correct me if i'm wrong.
They will change only for the objects that don't have this property changed explicitly. I changed your code on the last step to set 5 doors:
car.prototype.doors = 5;
https://jsfiddle.net/g1hrujL0/ in there you can see that the number of doors changes for the kea object which inherits the value from its prototype, however since we've explicitly changed this property for the honda object, its value is not changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With