admin管理员组

文章数量:1330380

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?

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?

Share asked Feb 23, 2011 at 22:58 Chris SimpsonChris Simpson 8,01012 gold badges53 silver badges70 bronze badges 2
  • 1 I've wondered this myself for quite a while. – McKayla Commented Feb 23, 2011 at 23:10
  • Have a look at my answer here. You could use this to extend the the object you get from JSON with the prototype of your "class". (or just copy the data from the JSON to an object of your "class" as @Box9 nicely demonstrates ;)) – Felix Kling Commented Feb 23, 2011 at 23:25
Add a ment  | 

1 Answer 1

Reset to default 6

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

本文标签: javascript casting an object that has been created with evalStack Overflow