Javascript 在数组中指定构造函数对象的最佳方法
我正在从服务器接收一组对象:Javascript 在数组中指定构造函数对象的最佳方法,javascript,arrays,constructor,coding-style,Javascript,Arrays,Constructor,Coding Style,我正在从服务器接收一组对象: [{name: 'Al'}, {name: 'Ann'}] 我想将它们转换为我创建的Person构造函数。现在,我正在这样做: function Person(attributes) { angular.extend(this, attributes); return this; } Person.prototype.getName = function() { return "My name is " + this.name
[{name: 'Al'}, {name: 'Ann'}]
我想将它们转换为我创建的Person构造函数。现在,我正在这样做:
function Person(attributes) {
angular.extend(this, attributes);
return this;
}
Person.prototype.getName = function() {
return "My name is " + this.name;
}
$scope.people = [];
$http.get('people')
.success(function(people) {
$scope.people = people.map(function(person, i) {
return new Person(person);
});
});
有人能想出更好的办法吗?不需要将数组中的每个对象都转换为所需的构造函数?也许可以告诉我的数组,数组中的所有对象在任何时候都是Person的实例。或者我可以将getName方法包含到$scope.people数组中,并让其中的对象调用位于其父数组中的方法
另外,如果有一种方法可以将对象转换为构造函数(以及它的原型方法),而无需像我在示例中所做的那样使用angular.extend,那就太好了。谢谢。写
Person.map()
作为包装器为您做这件事怎么样?我觉得您的解决方案很好。您是否对此进行了基准测试,并发现这是一个瓶颈或出于好奇而询问?任何方法最终都必须在某种程度上调用newperson()
。