Social Icons

Pages

Why and where i should use .prototype in Javascript?


In JavaScript there is no concept of class instead you create an object. It's not difficult, but a little foreign for somebody used to the classical way.

function Person (name,age) {
    this.name = name;
    this.age = age;
    this.getInfo = function() {
        return this.name + ' is ' + this.age + ' years old.' ;
    };
}

var niki= new Person('Niki',30);
niki.age = 29; //want it younger?
alert(niki.getInfo());

In this example however, you will end up with a separate copy of the function for each and every instance of the class, which is simply wasted memory, since the function is identical in each instance. The best way to define methods for classes in this method is to define them outside of the constructor function itself, but as attributes of its prototype. This can be done fairly simply as follows, and solves both issues:
 
function Person (name,age) {
    this.name = name;
    this.age = age;
}
  
Person.prototype.getInfo = function() {
    return this.name + ' is ' + this.age + ' years old.' ;
};

Using this syntax changes nothing in the way you instantiate the object and use its properties and methods.
"Prototype" allows to simulate classes in JavaScript, because JavaScript's inheritance system is -prototypical, and not class-based.
Just think of constructor functions as classes and the properties of the prototype as shared members, ie members which are the same for each instance. In class-based systems, methods are implemented the same way for each instance, so methods are normally added to the prototype, whereas an object's fields are instance-specific and therefore added to the object itself during construction.

 

Няма коментари:

Публикуване на коментар