简体   繁体   English

用对象文字定义构造函数原型

[英]Define constructor prototype with object literal

Which method below is best to define a constructor prototype and why? 以下哪种方法最适合定义构造函数原型,为什么?

Method 1: 方法1:

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

Method 2: 方法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). 如果要构造函数中分配原型,则无法使用对象文字来分配给Object.prototype(有时会很有用)。

Maybe you should write a little performance test using jsperf.com . 也许您应该使用jsperf.com编写一些性能测试。

You should use the method 1 . 您应该使用方法1 Using the method 2 , everytime you create a new instance, you will "re-create" the methods, since they are inside the constructor. 使用方法2 ,每次创建实例时,由于它们在构造函数中,因此您将“重新创建”这些方法。

var example = new MyConstructor();

under method 1: 在方法1下:

example.constructor === MyConstructor;

under method 2: 在方法2下:

typeof(example.constructor) === 'undefined';

The prototype object that comes with a function has a property constructor that points back to the function. 函数随附的原型对象具有指向该函数的属性constructor函数。 If you assign to the proprties of that object, you keep the constructor property. 如果分配给该对象的属性,则保留constructor属性。 If you overwrite the prototype property with a new object, you lose the constructor property. 如果使用新对象覆盖prototype属性,则会丢失constructor属性。

The performance difference is minimal. 性能差异很小。 Because constructor is so fragile, you can't really trust it, so I don't bother to preserve it. 因为constructor是如此脆弱,所以您不能真正信任它,因此我不必理会它。

Speaking further about the readability of your code, 再说说代码的可读性,

method 1 is better than method 2. 方法1优于方法2。

Method 2 spend one more indentation. 方法2再花一个缩进。 So it cause difficulty for reading codes. 因此,这会导致阅读代码困难。

Additionally, in my case, I can't inference that whether this function is prototype method or just static member function when we see a function name part in the lower part of codes. 另外,就我而言,当我们在代码的下部看到函数名称部分时,我无法推断此函数是原型方法还是静态成员函数。

Personally, in conclusion, I prefer method 2 if there not be much of a difference about performance. 总之,如果性能没有太大差异,我个人更喜欢方法2。

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM