How to set a prototype for a JSON object?

I get some JSON object from the server, and I want to "typecast" or "bless" it for an object with methods already defined. Is there a way to set a prototype for a simple JSON object?

function MyClass(someValue) { this.myProperty = someValue; } MyClass.prototype.someMethod = function() { return "Here " + this.myProperty + "!"}; var json = {myProperty : 'someValue'}; // ??? json.prototype = MyClass doesn't work, of course. var result = json.someMethod(); 

How can i do this?

+4
json javascript casting oop
source share
2 answers

OK Here is the answer (which is incompatible with IE):

 json.__proto__ = MyClass.prototype; 

Fortunately, I do not need% $@ $% # IE in my application.

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

+1
source share

Ok, I can suggest trying:

  • Adding the necessary 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 "creating" an 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 the JS framework for this. Or any other method you can think of :) My examples are easy, they can be extended to any complex that you need.

+3
source share

All Articles