【问题标题】:How to change array of one instance如何更改一个实例的数组
【发布时间】:2015-06-22 08:59:11
【问题描述】:

相关部分代码:

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");

因为“原型”将在所有实例之间共享我的颜色数组。

那么我怎样才能影响只有一个实例的颜色数组呢?

【问题讨论】:

  • 你在哪里创建 objWidget?您使用的是新关键字吗?
  • 似乎每个实例都有自己的color 数组,所以你应该没有任何问题。请创建一个可运行的示例。
  • $(".myClass").myObj( {colors:['#ccccff','#000099']} ); // 我不使用 new 关键字。
  • 那么return new myObj(...);到底是什么? ;) 在我看来像 new
  • 好的。图书馆确实使用“新”。

标签: javascript oop prototype


【解决方案1】:

您是否有可能为每个对象使用相同的实例,这就是为什么更改颜色值,它会随处更改。尝试为每个 .myClass 创建新实例

$hmi.fn.myObj = function (options, parentPage) {
    return this.each(function(){
        (new myObj(this.wgtId, options, parentPage));           
    });
};

如果您需要更多帮助,请告诉我。

【讨论】:

  • 试过了。但它没有帮助。 (需要在建议代码的第 3 行末尾添加 ')')。
【解决方案2】:

最后我通过使用简单变量 col0、col1 而不是使用数组来绕过这个问题。

不是最佳的,但解决了我当前的需求。 :(

【讨论】:

    猜你喜欢
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2020-08-24
    • 2022-10-15
    相关资源
    最近更新 更多