JavaScript Tutorial
indexjavascript history javascript versions language specificationsarrays built in objects call apply bind classes constructors closures environment setup error handling debugging functions interview questions objects programming constructs prototypes reactangularjsset map strings numbers testing frameworks variables data typesPrototypes in javascript
If you want to add new properties and methods to existing object you can easily do that. But if you want to add new properties and methods to existing class, you can not do that dynamically. You will have to modify the constructor of that class to add new properties and methods. That's when prototypes come in to picture. You can add properties and methods to class dynamically and all objects created from that class will inherit those properties and methods. e.g. all array objects inherit from Array.prototype.Prototype Example
//prototypes
let Car = function(make,price,features){
this.make=make;
this.price = price;
this.features = features;
}
let car4 = new Car("Honda", 20000, ['abs','alarm']);
console.log("car 4 " + JSON.stringify(car4));
//Below color property will not be inherited by car4 object
Car.color = "green";
console.log(car4.color);//undefined
Car.prototype.color = "green"
console.log(car4.color);//green
//conclusion - object will inherit properties from constructor or prototype only
Complex problems, Simple Solutions