Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating a new javascript class from an existing object

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

like image 820
jd. Avatar asked Feb 26 '10 15:02

jd.


People also ask

How do you apply dynamic class to an element?

In this article, we will see how to dynamically create a CSS class and apply to the element dynamically using JavaScript. To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript.

Is it possible to add new properties to a JavaScript object dynamically?

Use an index signature to dynamically add properties to an object, e.g. const obj: {[key: string]: any} = {} . Index signatures are used when we don't know all of the names of a type's properties and the type of their values ahead of time.

How do you create a dynamic object class?

You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.


2 Answers

JavaScript "classes", just like any other object, can be dynamically created. So, yes, this can be done.

You would do something like this in the code handling the AJAX response (assuming that the AJAX response was providing the name of the new "class", and it's in a variable called newClassName):

window[newClassName] = function() {
  // New class name constructor code
}

window[newClassName].prototype = {

  someProperty: "someValue",

  someMethod: function(a, b) {
  },

  someOtherMethod: function(x) {
  }
}
like image 80
jhurshman Avatar answered Oct 29 '22 10:10

jhurshman


This is actually the only for of inheritance that JavaScript has. JavaScript has prototypal inheritance (which can be used to recreate classical inheritance). That means that inheritance is from another object, not a class definition.

To create an object that has all the properties of another object is simple:

function Album() {
   // do whatever initialization you need to here, all the properties of album 
   // are available on 'this'
   // e.g.,
   doSomething(this.albumName);
}
Album.prototype = album;

var anotherAlbum = new Album();
like image 27
noah Avatar answered Oct 29 '22 09:10

noah