假设我从服务器接收到一些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 :)

推荐答案

Assuming your Object comes from some JSON library that parses the server output to generate an Object, it will not in general have anything particular in its prototype ; and two objects generated for different server responses will not share a prototype chain (besides Object.prototype, of course ;) )

如果您控制所有从JSON创建"Person"的地方,您可以反过来做:创建一个"空"Person对象(在其原型中使用类似fullName的方法),并使用从JSON生成的对象(使用$.extend、u.extend或类似的方法)对其进行扩展.

var p = { first : "John", last : "Doe"};

function Person(data) {
   _.extend(this, data);
}

Person.prototype.fullName = function() {
   return this.first + " " + this.last;   
}

console.debug(new Person(p).fullName());

Json相关问答推荐

如何使用JQ有条件 Select 值

过go 24小时内判断员事件的EventBridge事件模式

处理输入数据并转换为更简单的格式-PowerBI

当有2个嵌套数组时展平复杂的JSON

组合不同属性的Jolt Spec

使用 JSON 和相对日期设置日历视图中 SharePoint 列表项的背景 colored颜色 格式

GitHub Pages无法正确显示我的项目

使用 jq 从字符串列表开始创建对象

Oracle json 对象的最后一个值不在引号中

如何让 JSON.NET 忽略对象关系?

为什么在我们有 json_encode 时使用 CJSON 编码

单元测试球衣 Restful Services

如何将任意 json 对象发布到 webapi

Jackson 的@JsonView、@JsonFilter 和 Spring

apple-app-site-association json 文件是否会在应用程序中更新?

读取 HttpwebResponse json 响应,C#

如何使用 LWP 发出 JSON POST 请求?

ASP.NET MVC 读取原始 JSON 发布数据

运算符不存在:json = json

将 JSON 模式转换为 python 类