javascript - 如何更改一个实例的数组

标签 javascript oop prototype

代码的相关部分:

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/

相关文章:

javascript - 可以在公共(public)方法中访问私有(private)类属性吗?

javascript - 为什么 __proto__ 是相同的

javascript - TINYMCE V3 或 V4 在聚焦/模糊时显示/隐藏工具栏

Javascript - 从复选框返回值

java - 加法答案错误

javascript - 运行函数时出现意外输出。输出原型(prototype)代码

javascript - 使用 Object.create() 的对象创建模式

javascript - do-while 循环意外标识符

javascript - 在 Kendo UI 饼图上设置工具提示标签颜色

python - Python 何时从实例 __dict__ 返回到类 __dict__?