开发者

javascript: casting an object that has been created with eval

I have a set of javascript classes that I use throughout my app. In开发者_如何学JAVA 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?


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜