Use of 'prototype' vs. 'this' in J

2018-12-30 22:31发布

What's the difference between

var A = function () {
    this.x = function () {
        //do something
    };
};

and

var A = function () { };
A.prototype.x = function () {
    //do something
};

14条回答
牵手、夕阳
2楼-- · 2018-12-30 23:28

Prototype is the template of the class; which applies to all future instances of it. Whereas this is the particular instance of the object.

查看更多
公子世无双
3楼-- · 2018-12-30 23:29

As discussed in other answers, it's really a performance consideration because the function in the prototype is shared with all of the instantiations - rather than the function being created for each instantiation.

I put together a jsperf to show this. There is a dramatic difference in the time it takes to instantiate the class, although it is really only relevant if you are making many instances.

http://jsperf.com/functions-in-constructor-vs-prototype

查看更多
登录 后发表回答