How to set a prototype for a JSON object? How to set a prototype for a JSON object? json json

How to set a prototype for a JSON object?


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.


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).