在 JavaScript 代码中,我们当前使用 Method1 创建了很多对象(请参阅代码)。使用方法2会更好吗? (使用 .prototype)有什么好处? (特别对执行速度和内存使用感兴趣。)
var exampleObjectFunction1 = function(){ alert(this.exampleProperty1);};
var exampleObjectFunction2 = function(){ this.myFunction1(); };
var exeampleProperties = {
exampleProperty1: 'example',
exampleProperty2: 'example',
};
//Method1: Current instanciation method
function exampleObject1(properties) {
this.exampleProperty1 = properties.property1;
this.examplePropertyX = properties.propertyX;
this.exampleObjectFunction1 = exampleObjectFunction1;
this.exampleObjectFunction2 = exampleObjectFunction2;
};
var exampleObject1 = new exampleObject(properties);
//Method2: Using prototype (better?)
function exampleObject2(properties) {
this.exampleProperty1 = properties.property1;
this.examplePropertyX = properties.propertyX;
};
exampleObject2.prototype.exampleObjectFunction1 = exampleObjectFunction1;
exampleObject2.prototype.exampleObjectFunction2 = exampleObjectFunction2;
var exampleObject2 = new exampleObject2(properties);
编辑:我看到很多“构造函数与原型(prototype)”的比较。但是那里的“构造函数”代码通常会重新定义构造函数内的函数,而我在可重用变量中预先定义它们。我认为这是一个不同的方案,尽管我不太确定它是否更接近“原型(prototype)”或“构造函数”。
最佳答案
假设您创建了 1000 个 exampleObject1 对象和 1000 个 exampleObject2 对象。
如果您想覆盖所有 exampleObject1 对象的 exampleFunction1,则必须迭代所有对象并更改它。
如果您想对所有 exampleObject2 对象执行此操作,只需在一处更改它的原型(prototype)即可。
所以,从代码可扩展性的 Angular 来看,使用原型(prototype)是更好的选择。
关于javascript - 我们应该使用 .prototype 而不是当前的实例化方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34332010/