Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (13.1k points)

What is the difference between

var A = function () {

    this.x = function () {

        //do something

    };

};

And

var A = function () { };

A.prototype.x = function () {

    //do something

};

1 Answer

0 votes
by (7k points)

I think this would show you the actual difference in speed

Function directly on object:

function ExampleFn() {

    this.print = function() {

        console.log("Calling print! ");

    }

}

var objects = [];

console.time('x');

for (let i = 0; i < 2000000; i++) {

    objects.push(new ExampleFn());

}

console.timeEnd('x');

//x: 1151.960693359375ms

Function on prototype:

function ExampleFn() {

}

ExampleFn.prototype.print = function() {

    console.log("Calling print!");

}

var objects = [];

console.time('y');

for (let i = 0; i < 2000000; i++) {

    objects.push(new ExampleFn());

}

console.timeEnd('y');

//x: 617.866943359375ms

Interested in full stack development?  Check out the full stack developer course from Intellipaat.

Related questions

0 votes
1 answer
asked Aug 12, 2019 in Web Technology by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...