Functions inside constructor vs prototype

Like @Ersin Basaran mentioned, a function created inside the constructor is unique for every object instance, unlike when it is created using the prototype makes it the same function for every object instance.

However, after introducing classes in ES6 (ECMAScript2015), if you use a class to create a method instead of using a constructor function, and you create this method outside the constructor (but inside the class), it will be the same for every object instance, just like when using the prototype.

Here is an example of creating a fullName() method:

class Person {
    constructor () {
        var self = this;
        self.firstName = null;
        self.lastName = null;
    }
    fullName () {
        return self.firstName + self.lastName;
    }
}

Person.prototype.fullName2 = function () {
    return this.firstName + this.lastName;
};

var a = new Person();
var b = new Person();

console.log(a.fullName == b.fullName); // returns true
console.log(a.fullName2 == b.fullName2); // returns true

I hope this helps.


I perform a quick test. If you declare function in the constructor, two object instances have different function instances even after optimizations. However with prototype, you have only one instance of the function which explains the performance difference.

    var Person = function () {
        var self = this;
        self.firstName = null;
        self.lastName = null;
        self.fullName = function () {
            return self.firstName + self.lastName;
        };
    };

    Person.prototype.fullName2 = function () {
        return this.firstName + this.lastName;
    };

    var a = new Person();
    var b = new Person();

    console.log(a.fullName == b.fullName); // returns false
    console.log(a.fullName2 == b.fullName2); // returns true

Tags:

Javascript