javascript: casting an object that has been created with eval -
i have set of javascript classes use throughout app. in 1 case want eval json ajax response shape matches 1 of classes.
i'm using jquery parsejson method eval me.
the problem want call method defined in class know method won't exist on eval'd object.
what's nicest way make method available on new object. there way "cast" it?
there no concept of casting in javascript. instead, can modify class' constructor accept plain object. how depends on how you've set class, involve shallow copy of object new instance of class:
var myclass = function (obj) { (var in obj) { if (!obj.hasownproperty(i)) continue; this[i] = obj[i]; } // other class initialisation code };
then "cast" object this:
var result = new myclass(someobject);
if have multiple classes require this, may prefer create extend
function cloning (or if you're using jquery, function exists):
var extend = function (obj1, obj2) { (var in obj2) { if (!obj2.hasownproperty(i)) continue; obj1[i] = obj2[i]; } };
and "cast" this:
var result = new myclass(); extend(result, someobject);
Comments
Post a Comment