Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: casting an object that has been created with eval

I have a set of javascript classes that I use throughout my app. In one case I want to eval some json from an ajax response whose shape matches one of my classes.

I'm using the jquery parseJSON method to do the eval for me.

The only problem is I now want to call a method defined in my class however I know that method won't exist on the eval'd object.

What's the nicest way to make this method available on my new object. Is there a way to "cast" it?

like image 920
Chris Simpson Avatar asked Feb 23 '11 22:02

Chris Simpson


1 Answers

There is no concept of casting in JavaScript. Instead, you can modify your class' constructor to accept a plain object. How you do this depends on how you've set up your class, but could simply involve a shallow copy of the object into a new instance of the class:

var MyClass = function (obj) {
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        this[i] = obj[i];
    }
    // Other class initialisation code
};

Then "cast" your object like this:

var result = new MyClass(someObject);

If you have multiple classes that require this, you may prefer to create an extend function that does the cloning for you (or if you're using jQuery, this function already exists):

var extend = function (obj1, obj2) {
    for (var i in obj2) {
        if (!obj2.hasOwnProperty(i)) continue;
        obj1[i] = obj2[i];
    }
};

And then "cast" like this:

var result = new MyClass();
extend(result, someObject);
like image 104
David Tang Avatar answered Nov 04 '22 18:11

David Tang