我正在接收来自服务器的一些JSON对象,我想用已经定义好的方法''类型化'或'祝福'给一个对象。有没有办法为普通的JSON对象设置原型?如何设置JSON对象的原型?
function MyClass(someValue) {
this.myProperty = someValue;
}
MyClass.prototype.someMethod = function() { return "Here's " + this.myProperty + "!"};
var json = {myProperty : 'someValue'};
// ??? json.prototype = MyClass doesn't work, of course.
var result = json.someMethod();
我该怎么做?
我不知道这将在Safari或Chrome中起作用。你所描述的“其他可能性”实际上是最好的办法。 – Pointy 2010-11-04 13:54:52
@Pointy我测试过了,它确实如此。对IE来说,我发现了一个很酷的黑客,可以用来代替__proto__:http://www.webmasters.am/blog/tag/__proto__/。 – 2010-11-04 13:58:04
好吧,它不是标准化的(即使使用ECMAScript 5),请自行承担风险:-) – Pointy 2010-11-04 14:06:34