我想用一个不同的参数调用自定义对象的实例两次,问题是如果我设置它的配置属性,如果我创建 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