BalaKrishnan웃
BalaKrishnan웃

Reputation: 4557

How to create a collections for particular type in js?

In C# i have a collection for a type like this.

 public class scale
 {

 }


 public class scales : List<scale>
 {
     // some codes.
 }

For scale, I used the functions like this:

scale = function ( )
{

}

How to create a scales (collections for a function) in js?

Upvotes: 2

Views: 2471

Answers (2)

Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47961

You can use arrays in JavaScript:

var scales = [];
scales.push(new scale());
// and so on...

But JavaScript is a dynamically typed language. You cannot enforce compile-time type safety and create an array that can only have scale instances.

EDIT 1

The Array class already has a few helper methods. See here for more information.

EDIT 2

By the way, it is true that the scale variable you have defined above is a function, but when you create a new instance of scale using the new operator, what you get is not a function any longer, but an object. So you don't create a "collections for a function", but a collection for objects.

Upvotes: 3

Matthew Abbott
Matthew Abbott

Reputation: 61599

Javascript currently has no proper concept of a collection type, just use the array type:

var scales = [];
scales.push(new scale());

You can still access the associated properties:

scales[0].myProp = "Hello";

You could define scales to be a class itself:

var scales = function() { this._items = []; };
scales.prototype = {
   add: function(scale) {
       this._items.push(scale);
   }
}

Usage:

var scales = new scales();
scales.add(new scale());

Upvotes: 4

Related Questions