我有几个这样的javascript对象:
var object = {
name: "object name",
description: "object description",
properties: [
{ name: "first", value: "1" },
{ name: "second", value: "2" },
{ name: "third", value: "3" }
]
};现在,我想将这些对象更改为更智能的对象(添加一些方法等)。
首先,我创建了一个构造函数,如下所示:
SmartObject = function( object ){
this.name = object.name;
this.description = object.description;
this.properties = object.properties;
};
SmartObject.prototype.getName = function(){
return this.name;
};
SmartObject.prototype.getDescription = function(){
return this.description;
};
SmartObject.prototype.getProperies = function(){
return this.properties;
};然后我使用这个构造函数将我的对象更改为一个SmartObject实例,如下所示:
var smartObject = new SmartObject( object );这似乎是正确的面向对象的javascript代码来做这件事,但这感觉太复杂了,因为我实际上想做的就是添加一些方法,现在我在构造函数中将所有属性从object复制到SmartObject中。
在本例中只有3个属性和一些简单的方法,但在我的项目中有几十个(嵌套的)属性和更复杂的方法。
所以我试了一下:
object.__proto__ = SmartObject.prototype;这似乎产生了完全相同的结果,而且看起来容易得多(在这个例子中查看 )。
这是将原型添加到我的对象的适当且可接受的方式吗?或者是违反了面向对象模式的,被认为是糟糕的实践,我是否应该继续像以前那样做(使用构造函数)。
或者,是否有另一种更可接受的方法来将方法添加到我现有的对象中,而无需通过构造函数拉取它?
我试图在StackOverflow上找到这样的例子,但当我搜索时,我总是得到扩展现有javascript类的原型的例子。如果有这样的问题,请随时将其标记为副本,我将再次结束我的问题。
发布于 2016-06-17 20:23:54
正如我之前提到的,更改对象的原型将对代码的性能产生严重影响。(顺便说一句,我从来没有花时间来衡量影响)。This MDN page explains。
但是,如果您问题是关于样板,那么您可以很容易地为对象创建一个通用工厂,例如:
function genericFactory(proto, source) {
return Object.keys(source).reduce(function(target, key) {
target[key] = source[key];
return target;
}, Object.create(proto));
}现在,您可以通过将SmartObject.prototype和object作为参数传递来使用它,如下所示:
var smartObject = genericFactory(SmartObject.prototype, object);发布于 2016-06-17 21:16:17
结合来自@SebastienDaniel他的答案的Object.create()和@bloodyKnuckles他的评论,以及@nnnnnn在他的评论中建议的Object.assign()方法,我用以下简单的代码实现了我想要的:
var smartObject = Object.assign( Object.create( SmartObject.prototype ), object );发布于 2016-06-18 01:45:54
,所以我尝试了这个:
object.__proto__ = SmartObject.prototype;
..。
这是将原型添加到我的对象的适当且可接受的方式吗?或者这违反了面向对象的模式,被认为是不好的做法,我应该继续像以前那样做(使用构造函数)。
我建议不要这样做,因为:
__proto__属性仅在JavaScript规范的附录中定义,并且仅针对浏览器(尽管该规范确实要求浏览器实现它)。非特定于浏览器的方式是Object.setPrototypeOf(object, SmartObject.prototype);,但请参阅#1和#2。你会担心它是多余的或重复的,无论是在编码级别还是在内存级别(我不确定)。如果你从一开始就接受你的SmartObject,而不是先创建object,然后再添加smarts,就不是这样了:
var SmartObject = function(name, description, properties) {
this.name = name;
this.description = description;
this.properties = properties;
};
SmartObject.prototype.getName = function(){
return this.name;
};
SmartObject.prototype.getDescription = function(){
return this.description;
};
SmartObject.prototype.getProperies = function(){
return this.properties;
};
var object = new SmartObject(
"object name",
"object description",
[
{ name: "first", value: "1" },
{ name: "second", value: "2" },
{ name: "third", value: "3" }
]
);
var anotherObject = new SmartObject(
/*...*/
);
var yetAnotherObject = new SmartObject(
/*...*/
);或者更好的是,使用ES2015 (您现在可以在Babel这样的转译器中使用它):
class SmartObject {
constructor() {
this.name = name;
this.description = description;
this.properties = properties;
}
getName() {
return this.name;
}
getDescription() {
return this.description;
}
getProperies(){
return this.properties;
}
}
let object = new SmartObject(
"object name",
"object description",
[
{ name: "first", value: "1" },
{ name: "second", value: "2" },
{ name: "third", value: "3" }
]
);
let anotherObject = new SmartObject(
/*...*/
);
let yetAnotherObject = new SmartObject(
/*...*/
);您已经说过,您不能从一开始就接受SmartObject,因为它们来自JSON源。在这种情况下,您可以使用reviver函数将SmartObject合并到JSON解析中:
var objects = JSON.parse(json, function(k, v) {
if (typeof v === "object" && v.name && v.description && v.properties) {
v = new SmartObject(v.name, v.description, v.properties);
}
return v;
});虽然这确实意味着首先创建对象,然后创建_re_created,但创建对象是一个非常廉价的操作;下面的示例显示了在解析20k对象时使用和不使用复活器时的时间差:
var json = '[';
for (var n = 0; n < 20000; ++n) {
if (n > 0) {
json += ',';
}
json += '{' +
' "name": "obj' + n + '",' +
' "description": "Object ' + n + '",' +
' "properties": [' +
' {' +
' "name": "first",' +
' "value": "' + Math.random() + '"' +
' },' +
' {' +
' "name": "second",' +
' "value": "' + Math.random() + '"' +
' }' +
' ]' +
'}';
}
json += ']';
var SmartObject = function(name, description, properties) {
this.name = name;
this.description = description;
this.properties = properties;
};
SmartObject.prototype.getName = function() {
return this.name;
};
SmartObject.prototype.getDescription = function() {
return this.description;
};
SmartObject.prototype.getProperies = function() {
return this.properties;
};
console.time("parse without reviver");
console.log("count:", JSON.parse(json).length);
console.timeEnd("parse without reviver");
console.time("parse with reviver");
var objects = JSON.parse(json, function(k, v) {
if (typeof v === "object" && v.name && v.description && v.properties) {
v = new SmartObject(v.name, v.description, v.properties);
}
return v;
});
console.log("count:", objects.length);
console.timeEnd("parse with reviver");
console.log("Name of first:", objects[0].getName());
在我的机器上,它的时间大约翻了一番,但我们谈论的是~60ms到~120ms,所以从绝对值来看,没什么好担心的--这是针对20k对象的。
或者,您可以混合使用您的方法,而不是使用原型:
// The methods to mix in
var smartObjectMethods = {
getName() {
return this.name;
},
getDescription() {
return this.description;
},
getProperies() {
return this.properties;
}
};
// Remember their names to make it faster adding them later
var smartObjectMethodNames = Object.keys(smartObjectMethods);
// Once we have the options, we update them all:
objects.forEach(function(v) {
smartObjectMethodNames.forEach(function(name) {
v[name] = smartObjectMethods[name];
});
});ES2015有Object.assign,您可以使用它来代替smartObjectMethodNames和内部forEach
// Once we have the options, we update them all:
objects.forEach(function(v) {
Object.assign(v, smartObjectMethods);
});无论哪种方式,它的都稍微降低了内存效率,因为每个对象最终都有自己的getName、getDescription和getProperties属性(函数不是重复的,它们是共享的,但是引用它们的属性是重复的)。不过,这不太可能成为问题。
下面是一个包含20k对象的示例:
var json = '[';
for (var n = 0; n < 20000; ++n) {
if (n > 0) {
json += ',';
}
json += '{' +
' "name": "obj' + n + '",' +
' "description": "Object ' + n + '",' +
' "properties": [' +
' {' +
' "name": "first",' +
' "value": "' + Math.random() + '"' +
' },' +
' {' +
' "name": "second",' +
' "value": "' + Math.random() + '"' +
' }' +
' ]' +
'}';
}
json += ']';
var smartObjectMethods = {
getName() {
return this.name;
},
getDescription() {
return this.description;
},
getProperies() {
return this.properties;
}
};
var smartObjectMethodNames = Object.keys(smartObjectMethods);
console.time("without adding methods");
console.log("count:", JSON.parse(json).length);
console.timeEnd("without adding methods");
console.time("with adding methods");
var objects = JSON.parse(json);
objects.forEach(function(v) {
smartObjectMethodNames.forEach(function(name) {
v[name] = smartObjectMethods[name];
});
});
console.log("count:", objects.length);
console.timeEnd("with adding methods");
if (Object.assign) { // browser has it
console.time("with assign");
var objects = JSON.parse(json);
objects.forEach(function(v) {
Object.assign(v, smartObjectMethods);
});
console.log("count:", objects.length);
console.timeEnd("with assign");
}
console.log("Name of first:", objects[0].getName());
https://stackoverflow.com/questions/37881208
复制相似问题