0

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?

2
  • 1
    Do you know what the prototype is? Commented Aug 10, 2017 at 13:35
  • search prototype on google, explanations and tutorials galore. hmm.. and they thought it would be a good idea to add class to javascript. Commented Aug 10, 2017 at 14:35

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Good explanation. Maybe also include a link to the stackoverflow docs? stackoverflow.com/documentation/javascript/592/inheritance/723/…
@evolutionxbox Thank you. It seems that no new links to documentation are possible. SO doesn't let me save it and points me here: meta.stackoverflow.com/questions/354217/…
Aw man. Sad times. I didn't know about this decision. Thanks for considering it anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.