且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用对象字面量定义构造函数原型

更新时间:2023-09-24 17:09:52

我会说没什么区别。使用一个对象字面量来分配给Object.prototype是一个你不能做的事情,如果你在 中分配原型的构造函数(有时候可能会有用)。



也许您应该使用 jsperf.com 撰写一个小的性能测试。


Which method below is best to define a constructor prototype and why?

Method 1:

MyConstructor.prototype.myFunction1 = function(){};
MyConstructor.prototype.myFunction2 = function(){};

Method 2:

MyConstructor.prototype = {
    myFunction1: function(){},
    myFunction2: function(){}
};

I'm mostly concerned about speed. Thanks!

I would say there wouldn't be much of a difference. Using an object literal to assign to the Object.prototype is something you can't do if you're assigning the prototype within the constructor (which can be usefull sometimes).

Maybe you should write a little performance test using jsperf.com.