English 中文(简体)
Changing an Object s Type in JavaScript
原标题:

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?

最佳回答

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:

var obj = {
    name : "Jeremy"
};

function CustomType() {
    this.name = this.name || "someValue";
    this.greeting = "Hi";
}

CustomType.prototype.sayHi = function() {
    alert(this.greeting + ", " + this.name);
};

obj.__proto__ = CustomType.prototype;
obj.constructor.call(obj);

obj.sayHi();
问题回答

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:

var myobj = new Object()
myobj.name = "Fred"

Then I will create some class that you would like to be able to assign to myobj:

function Speaker() {
    this.speak = function() {
        window.alert("Hello, " + this.name);
    }
}

This new Speaker class has some useful functionality: it can use the method speak() to output useful information:

var s = new Speaker()
s.name = "Sally"
s.speak()

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:

myobj.speak = s.speak

Now when I execute this:

myobj.speak()

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.

If you don t need constructor, you can do as:

Object.assign(new CustomType, {});

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.

function Object1() {
  this.aValue = "10";
}

function CustomObject() {
  this.customValue = "6";
}

function convertToCustom(obj) {
  var custom = new CustomObject();
  for( var key in obj ) {
    custom[key] = obj[key];
  }
  return custom;
}

var obj = new Object1();
var custom = convertToCustom(obj);

console.log(custom.customValue); // <- 6
console.log(custom.aValue);      // <- 10

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:

var obj = {
name : "Jeremy"
};


function CustomType() {
}

CustomType.prototype.init = function(){
    this.name = this.name || "someValue";
    this.greeting = "Hi";
    return this; //let s make it fluent
}

CustomType.prototype.sayHi = function() {
    console.log(this.greeting + ", " + this.name);
};

function extend(obj, props) { 
    for(prop in props) { 
        if(props.hasOwnProperty(prop)) { 
            obj[prop] = props[prop]; 
        } 
    }
    return obj; //let s make it fluent
}

obj = extend(Object.create(CustomType.prototype), obj).init();

obj.sayHi();




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签