更好的JavaScript对象初始化

时间:2016-02-07 11:54:39

标签: javascript oop

我有一种对象,我已经这样声明了:

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'];
...

我用:

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

在某些情况下,我会同时实例化该类型的多个对象。该对象也有功能,我想启动它有点清洁,我怎么能这样做,但保持我的功能?见这里:

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

或者至少与此相似。

3 个答案:

答案 0 :(得分:3)

您可以将要传递给构造函数的参数包装到'选项'参数。

如果你想继续使用' Stream',请使用它的原型来定义它的功能,这将使它们在所有Stream的实例上都可用。

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

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

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

用法:

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

答案 1 :(得分:1)

你可以使用像这样的匿名函数



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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以在Stream Constructor中传递配置对象,然后从该

获取值
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'];
}

你可以按照你提到的那样打电话

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