Alex Rivera | Logout

Dynamically creating a new javascript class from an existing object

Asked 2010-02-26T15:03:10.567
18

Say I have the following code:

var album = new MyObject('album');

Assume that when the object is constructed, a bunch of properties relative to only albums are loaded via AJAX. Would it be possible to create an Album class so that at a later point, I may just do this:

var anotherAlbum = new Album();

The Album constructor would automatically set the properties that are unique to album objects, based on what was loaded when creating MyObject('album')

Edit
Report

1 Answer

12

JavaScript is prototypal, not classical, so if you think in terms of classes, you're doing it wrong.

You don't have to use the new operator at all. You can create a new object using the object literal:

var myObject = {attr1: 'val1', attr2: 'val2'};

Then you can create a new instance of that object:

var mySecondObject = Object.create(myObject);

Now you can change the attributes of mySecondObject, and if it has methods you can overload them just as easily:

mySecondObject.attr1 = "Hello";

mySecondObject.attr2 = function() {
                           return "World!";
                       };

And then mySecondObject will of course have all the properties that you gave myObject at creation.

Be aware that this is a simple version, and that this leaves all attributes 'public'. If you need some privacy, it can be achieved by adding some functions to the mix. It's a bit more complicated though, so let me know if you're interested...

answered 2010-02-26T15:40:59.343

Your Answer