0

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

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

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

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
4

1 回答 1

0

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

    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'
});
于 2013-05-31T20:13:02.127 回答