调用带有不同参数的自定义对象实例
Call instances of custom object with different parameters
我想调用一个自定义对象的实例两次与一个参数不同,问题是,如果我设置它的配置属性它相应地改变,如果我创建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'
});
相关文章:
- 从HTTPGET返回一个自定义对象列表,以便在Angular 2应用程序中使用
- 使用数组自定义对象
- 使用带有自定义对象作为属性的jQuery.extend时出现意外行为
- 在JavaScript中定义自定义对象和函数(第2部分)
- 在JavaScript中定义自定义对象和函数
- 如何获得一个动态增长的自定义对象的Javascript数组
- Angular Schema Form-自定义对象编辑器
- 使用JavaScript将自定义对象添加到文档中
- 序列化具有方法的自定义对象.序列化后删除的方法-要采取的步骤
- 正在将img/文件上载到Quickbloxx自定义对象API
- 生成自定义对象调用
- 将自定义对象的猫鼬 PUT 实现到复杂架构中时出现问题
- 如何在 Javascript 中制作自定义对象数组
- 使 HTML 元素从自定义对象继承事件
- Javascript错误消息,自定义对象表示
- 在自定义对象上使用 jQuery 等选择器
- 自定义对象内的范围问题
- 自定义对象中的变量范围
- 如何使用Visual Force和Javascript在Salesforce中的自定义对象中获取自定义字段值
- 自定义对象/类型 Javascript