I have an array of existing object defined with JSON. The objects are obviously of the Object type. How do I associate them with a custom object type to give them specific functionality?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
The way that'll work in all browsers is to either augment each item in the array with the properties and methods you want, or pass the object to a constructor and create a new object based on the old object's properties and methods.
Or if you don't care about IE:
If you don't need constructor, you can do as:
I do not believe that there is any way to change the type of an object once it is created. Fortunately, you probably don't actually need to change the class, of your objects -- you will probably be satisfied with giving the objects some new methods and other functionality. (The only real difference is what would happen if you CHANGED the class, and most people don't change classes while code is running.)
I'll work an example for you. First, I'll create a simple object to represent the JSON objects you have:
Then I will create some class that you would like to be able to assign to
myobj
:This new
Speaker
class has some useful functionality: it can use the methodspeak()
to output useful information:Executing that gave me the message "Hello, Sally". Unfortunately, you don't want a NEW object (like
s
) with this functionality, you want the existing object (myobj
) to have it. Here is how you do that:Now when I execute this:
I see the message "Hello, Fred".
To summarize: create an object that does what you want. Copy all the methods (and any helper variables) into your new object. Except for some unusual uses of inheritance, this will make your new object behave as desired.
As a complement to Jeremy's answer, you could use Object.create instead of directly playing with proto. You'll also need an "extend" function.
So, given Jeremy's example, you could have something like this:
If you want to use a specific method on them you can use apply/call.
Or you can copy the methods for your custom object.