Company where i'm working right now they are writing sth like this all the time ...
function art() {
};
art.prototype = { sth functions, var's }
or
function art() {
};
art.prototype = (function () {
return{
sth functions, vars
}
})();
what is a purpose of this habits, that is changing something?
1 Answer 1
Prototypes are one of the core features of JavaScripts. Prototype is basically an object from which other objects inherit properties. Every object has its own prototype property from which it inherits its members (properties, methods).
Take this classical polymorphism example:
// Car Top Class
var Car = function (brand) {
this.brand = brand;
};
Car.prototype.say = function () {
return 'I am ' + this.brand;
};
// Models inheriting from car
function Mercedes() {
this.fourwheels = '4Matic';
};
Mercedes.prototype = new Car('Mercedes-Benz');
function Audi() {
this.fourwheels = 'Quatro';
};
Audi.prototype = new Car('Audi');
// ---
var mercedes = new Mercedes();
var audi = new Audi();
console.log(`${ mercedes.say() } with ${ mercedes.fourwheels }`);
console.log(`${ audi.say() } with ${ audi.fourwheels }`);
..especially see the Mercedes.prototype = new Car('Mercedes-Benz'); by allocating new instance of Car to Mercedes prototype we are achieving inheritance (Mercedes will receive the Car's members) which plays the key role to polymorphism in this example.
classto javascript.