代码的相关部分:
function myObj(wgtId, options, parentPage) {
if (!wgtId) return;
this.colors=['red','pink'];
hmiWidget.call(this, wgtId, options, parentPage);
}
myObj.prototype = new hmiWidget(); // Inheriting the base class Widget
myObj.prototype.setValue = function (newValue) {
var index = newValue;
var color = this.colors[index];
this.elem.style.backgroundColor = color;
};
$hmi.fn.myObj = function (options, parentPage) {
return new myObj(this.wgtId, options, parentPage);
};
用法:
$(".myClass").myObj( {colors:['#ccccff','#000099']} ); // start with blue
. . .
objWidget.setValue(newVal);
所有这些都运作良好。
现在我需要更改特定实例的颜色数组。
我尝试使用 -
objWidget.colors[0] = "#ccffcc";
但它影响了所有实例。 (我不明白为什么所有实例都会受到影响。)
来自 Javascript object members that are prototyped as arrays become shared by all class instances 我知道我无法添加和使用
code:
myObj.prototype.setColor = function (index, newColor) {
this.colors[index] = newColor;
}
usage:
objWidget.setColor(0, "#009900");
因为“原型(prototype)”将在所有实例之间共享我的颜色数组。
那么如何才能影响仅一个实例的颜色数组呢?
最佳答案
您是否可能为每个对象使用相同的实例,这就是为什么更改颜色值,它会随处更改。尝试为每个 .myClass 创建新实例
$hmi.fn.myObj = function (options, parentPage) {
return this.each(function(){
(new myObj(this.wgtId, options, parentPage));
});
};
如果您需要更多帮助,请告诉我。
关于javascript - 如何更改一个实例的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30975833/