How to set a prototype for a JSON object?

2019-04-10 09:45发布

I am receiving some JSON object from the server, and I want to 'typecast' or 'bless' it to an object with already defined methods. Is there any way to set a prototype for a plain JSON object?

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();

How can I do that?

2条回答
放荡不羁爱自由
2楼-- · 2019-04-10 10:25

Well, I can suggest to try out these:

  • By adding the needed functions to ALL Javascript objects (bad practice)

    Object.prototype.lol = function() { alert(this.a); };
    var x = {a : 'b'};
    x.lol();
    
  • By "extending" JSON with a function:

    var json = {a : 'b', b : 123};
    function extend(obj) {
        obj.func1 = function(param) {
            alert(this[param]);
        }
    }
    extend(json);
    json.func1('b');
    
  • By "making" the object into a function:

    var json = {a : 'b', b : 123};
    function extendToFunc(obj) {
        var theLibrary = function(obj) {
            /**
             * The same as above.
            */
            this.func1 = function(param) {
                 alert(obj[param]);
            }
        };
        return new theLibrary(obj);
    }
    var jsonFunc = extendToFunc(json);
    jsonFunc.func1('b');
    

Or you can use a JS framework for that. Or any other method that you can think of :) My examples are easy, they can be extended into anything sophisticated you need.

查看更多
▲ chillily
3楼-- · 2019-04-10 10:34

OK. Here is the answer (which is IE-incompatible):

json.__proto__ = MyClass.prototype;

Thankfully, I don't need no %$@$%# IE in my application.

(When I do, there is another possibility: create a wrapper function in MyClass prototype which copies all properties from JSON to the new object; shallow-copying should be enough).

查看更多
登录 后发表回答