调用带有不同参数的自定义对象实例

Call instances of custom object with different parameters

本文关键字:自定义 对象 实例 参数 调用      更新时间:2023-09-26

我想调用一个自定义对象的实例两次与一个参数不同,问题是,如果我设置它的配置属性它相应地改变,如果我创建2个实例,但如果我不指定属性时调用对象的第二个实例,它从第一个实例继承设置参数。

我希望第二个实例使用默认参数,除非它是在调用时手动设置的。

我尝试创建一个元素变量并将其添加到查询的元素中,但它不起作用。

HTML:

<div class="parent">
<div class="test"><p>test</p></div>
</div>
<div class="parent-second">
<div class="test"><p>test</p></div>
</div>

JS:

(function() {
// Utility
if ( typeof Object.create !== 'function' ) {
    Object.create = function( obj ) {
        function F() {};
        F.prototype = obj;
        return new F();
    };
}
var objTest = {
    config: {
        value: 'some text'
    },
    init: function(elem, config) {
        var self = this;
        this.elem = elem;
        $.extend(this.config, config);
        this.doIt();
    },
    doIt: function() {
        var self = this;
        $(self.elem + ' .test p').text(this.config.value);
        console.log($(self.elem + ' .test p'));
    }
};
var parent = Object.create( objTest );
parent.init('.parent', {
    value: 'first div text'
});
// if you comment out the value parameter from the following instance, it will inherit from previous object instance
var parentSecond = Object.create( objTest );
parentSecond.init('.parent-second', {
    value: 'second div text'
});


})(); // end self invoking function

问题是你的配置对象在你的对象的所有实例之间得到共享。因此,您必须为每个实例创建一个新的配置对象。

    var objTest = {
        init: function(elem, config) {
            var self = this;
            this.elem = elem;
            if(!this.config)
            {
                this.config = {
                value: 'some text'
                };
            }
            $.extend(this.config, config);
            this.doIt();
        },
        doIt: function() {
            var self = this;
            $(self.elem + ' .test p').text(this.config.value);
            console.log($(self.elem + ' .test p'));
        }
    };

这对你来说很好。虽然我更喜欢使用原型方法。

function objTest ()
{
    //you could also merge init function in this constructor
    this.config = {
        value: 'some text'
    };
}
objTest.prototype = {
    init = function (elem, config) {
       var self = this;
        this.elem = elem;
        if(!this.config)
        {
            this.config = {
            value: 'some text'
            };
        }
        $.extend(this.config, config);
        this.doIt();
    },
    doIt: function() {
        var self = this;
        $(self.elem + ' .test p').text(this.config.value);
        console.log($(self.elem + ' .test p'));
    }
}  

var parent = new objTest();
parent.init('.parent', {
    value: 'first div text'
});
var parentSecond = new objTest();
parentSecond.init('.parent-second', {
    value: 'second div text'
});