TemporaryName
TemporaryName

Reputation: 505

Nicer JavaScript object initialization

I have a type of object which I've declared like this:

function Stream(id, info, container){
    var self = this;

    this.id = id;
    this.paddedId = ("00000" + this.id).substr(-5,5);
    this.live = info['live'];
    this.autoplay = info['autoplay'];
...

I instantiate that with:

var stream = new Stream(1, streamInfo, "stream");

On some occasions I instantiate several objects of that type at once. The object also has functions, I want to initiate it a bit cleaner, how can I do it like this, but keep my functions? See here:

var stream = new Stream({
        'id': 1
        'live': true
        'autoplay': false
     });

Or at least something similar to this.

Upvotes: 0

Views: 72

Answers (3)

mati.o
mati.o

Reputation: 1768

You can wrap the parameters you want to pass to the constructor into a 'options' parameter.

If you want to keep function on 'Stream', use its prototype to define functions on it which will make them available on all Stream's instances.

function Stream(options){
   this.id = options.id;
   this.autoplay = options.autoplay;
   // ... rest of variable initialization
}

Stream.prototype.foo = function() {
  // ...
}
 
Stream.prototype.bar = function() {
 // ...
}

Usage :

var stream = new Stream({ id : 'myId', autoplay : true });
stream.foo();
stream.bar();

Upvotes: 3

WalksAway
WalksAway

Reputation: 2819

You could use anonymous functions like this

var MyClass = (function () {

    var self = function (options) {

        // these will be our default options
        this.options = {
            name: 'John',
            lastName: 'doe'
        }

        // here we just extend the object
        $.extend(this.options, options);
    };

    self.prototype.get = function (attr) {
        return this.options[attr];
    };

    self.prototype.set = function (attrName, attrValue) {
        this.options[attrName] = attrValue;
    };

    self.prototype.whatsMyName = function () {
        $('.' + this.get('name')).html(this.get('name') + ' ' + this.get('lastName'));
    };

    return self;
})();

var Tom = new MyClass({
    name: 'Tom',
    lastName: 'Mathew'
});

var Allen = new MyClass({
    name: 'Allen',
    lastName: 'C'
});

Tom.whatsMyName();
Allen.whatsMyName();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div class="Tom"></div>
<div class="Allen"></div>

Upvotes: 1

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

You can pass a config object in Stream Constructor and then get values from that

function Stream(fonfig){
   var self = this;
   var info = config.info || {};
   this.id = config.id;

   this.paddedId = ("00000" + this.id).substr(-5,5);
   this.live = info['live'];
   this.autoplay = info['autoplay'];
}

and you can call as you mentioned

var stream = new Stream({
    'id': 1
    'live': true
    'autoplay': false
 });

Upvotes: 0

Related Questions