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?
The Object. setPrototypeOf() method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null. All JavaScript objects inherit properties and methods from a prototype. It is generally considered the proper way to set the prototype of an object.
To create an object we need to use opening and closing curly braces {} and then inside of that we'll put all of the key value pairs that make up our object. Every single property inside the JSON is a key value pair. The key must be surrounded by double "" quotes followed by a colon : and then the value for that key.
The prototype of an object is referred to by the prototype property of the constructor function that creates and initializes the object. The isPrototypeOf() method provides a way to determine if one object is the prototype of another. This technique can be used to determine the class of an 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With