使用对象字面量定义构造函数原型 [英] Define constructor prototype with object literal

查看:401
本文介绍了使用对象字面量定义构造函数原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下哪种方法最适合定义构造函数原型?为什么?



方法1:

  MyConstructor.prototype.myFunction1 = function(){}; 
MyConstructor.prototype.myFunction2 = function(){};方法2:

 

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

我最关心的是速度。谢谢!

解决方案

我会说没什么区别。使用一个对象字面量来分配给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.

这篇关于使用对象字面量定义构造函数原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆