更好的JavaScript对象初始化

Nicer JavaScript object initialization

本文关键字:初始化 对象 JavaScript 更好      更新时间:2023-09-26

我有一个对象类型,我这样声明:

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
     });

或者至少与此类似。

您可以将要传递给构造函数的参数包装为"options"参数。

如果要将函数保留在"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();

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

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>

您可以在 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
 });