【发布时间】: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