有没有办法使用JavaScript原型或其他方式将函数注入从JSON数据创建的数据结构?我有一个返回联系人列表的休息服务。该联系人具有firstName,lastName。我想将getFullName()函数添加到列表中的每个联系人结构中。
我想做类似以下的事情。
var contacts = [{firstName: 'Stephen', lastName: 'Hawking'},
{firstName: 'Nicolas', lastName: 'Tesla'},
{firstName: 'Dean', lastName: 'Kamen'}
];
for(var i = 0; i < contacts.length; i++){
var contact = contacts[i];
//inject defined functions if it is not yet injected.
//contact.inject(definedFunctions); //How do we do this
console.log(contact.getFullName());
}
答案 0 :(得分:2)
您应该围绕该数据创建一个包装器:
function Contact(data) {
this.data = data;
}
Contact.prototype.getFullName = function () {
return this.data.firstName + ' ' + this.data.lastName;
}
var contacts = [...]
.map(function (data) {
return new Contact(data);
});
答案 1 :(得分:1)
无法将函数放入JSON数据中,因为它只是文本。将JSON解析为JavaScript对象后,您可以轻松地将属性添加到函数对象中:
for(var i = 0; i < contacts.length; i++){
var contact = contacts[i];
contact.getFullName = function(){
return this.firstName + ' ' + this.lastName;
};
console.log(contact.getFullName());
}
答案 2 :(得分:0)
使用&#34; bind()&#34;:
var contacts = [{firstName: 'Stephen', lastName: 'Hawking'},
{firstName: 'Nicolas', lastName: 'Tesla'},
{firstName: 'Dean', lastName: 'Kamen'}
];
var getFullName = function() {
return this.firstName + ' ' + this.lastName;
};
for(var i = 0; i < contacts.length; i++){
var contact = contacts[i];
contact.getFullName = getFullName.bind(contact);
// Or:
//contact['getFullName'] = getFullName.bind(contact);
console.log(contact.getFullName());
}