假设我从服务器接收到一些JSON对象,例如Person对象的一些数据:
{firstName: "Bjarne", lastName: "Fisk"}
现在,我想在这些数据之上有一些方法,例如计算全名:
fullName: function() { return this.firstName + " " + this.lastName; }
这样我就可以
var personData = {firstName: "Bjarne", lastName: "Fisk"};
var person = PROFIT(personData);
person.fullName(); // => "Bjarne Fisk"
What I basically would want to do here, is to add a method to the object's prototype. The fullName()
method is general, so should not be added to the data object itself. Like..:
personData.fullName = function() { return this.firstName + " " + this.lastName; }
... 会导致大量冗余;而且可以说是"污染"了数据对象.
将此类方法添加到简单数据对象的当前最佳实践方式是什么?
EDIT:个
Slightly off topic, but if the problem above can be solved, it would be possible to do some nice pseudo-pattern matching
like this:
if ( p = Person(data) ) {
console.log(p.fullName());
} else if ( d = Dog(data) ) {
console.log("I'm a dog lol. Hear me bark: "+d.bark());
} else {
throw new Exception("Shitty object");
}
Person
and Dog
will add the methods if the data
object has the right attributes. If not, return falsy (ie. data does not match/conform).
BONUS QUESTION: Does anyone know of a library that either uses or enables this (ie makes it easy)? Is it already a javascript pattern? If so, what is it called; and do you have a link that elaborates? Thanks :)