【问题标题】:Javascript object member variable not cloningJavascript对象成员变量不克隆
【发布时间】:2013-08-22 14:43:04
【问题描述】:

我从 EASELJS 库继承了一个对象。 为了简化问题,我将代码简化为最小形式。

我有一堂课:

this.TESTProg = this.TESTProg || {};

(function() {
    var _jsbutton = function(x, y, text, icon) {
        p.init(x, y, text, icon);
    };

    var p = _jsbutton.prototype = new createjs.Container();

    p.x = 0;
    p.y = 0;
    p.text = null;
    p.icon = null;

    p.init = function(x, y, text, icon) {
        this.x = 0 + x;
        this.y = 0 + y;
        this.text = "" + text;
        this.icon = null;
    };

    TESTProg._jsbutton = _jsbutton;
})();

然后我在另一个js对象中使用它:

    var buttoncancel = new SJSGame._jsbutton(
            profileselConfig.cancelx,    //this is defined in another jsfile:
            profileselConfig.cancely,
            "cancel", "_cancel.png");

    console.log( buttoncancel.y );  //this gives 240

    var buttoncancel2 = new SJSGame._jsbutton(
            profileselConfig.cancelx,
            profileselConfig.cancely - 40,
            "cancel", "_cancel.png");

    console.log( buttoncancel.y );    //this gives 200
    console.log( buttoncancel2.y );   //this gives 200

    buttoncancel2.y = 100;
    console.log( buttoncancel.y );    //this now gives 200 (not changed by the second object)
    console.log( buttoncancel2.y );   //this now gives 100

配置文件:

var _profileselConfig = function(){
    this.cancelx = 0;
    this.cancely = 240;
};

profileselConfig = new _profileselConfig();

我做错了什么?

我已经在使用 0 + 来避免传递引用,但它不起作用。我现在该怎么办?有什么建议么?谢谢。

【问题讨论】:

标签: javascript html class object easeljs


【解决方案1】:

您可能应该在构造函数中调用this.init 而不是p.init

当您调用p.init 时,init 内部的this 指的是原型。因此,无论何时创建实例,您的 p.init 调用都会修改 all _jsbutton 对象的原型。

这就是为什么两个按钮具有相同的 x/y 值的原因:它们都从同一个原型中获取它们的位置,并且最后运行的构造函数设置了原型值。当您在构造函数之外设置 buttoncancel2.y 时,您为该实例提供了自己的 y 属性,因此它不再使用共享原型值。

如果您在构造函数中调用this.init,那么init 中的this 将引用您新创建的实例。实例将不再使用 xytexticon 的共享原型值。

旁注:“我已经在使用 0 + 来避免传递引用”——这不是必需的,因为原始类型总是被复制的。

【讨论】:

  • 谢谢,所以即使我的 p 是一个不区分不同对象的新实例。明白了
猜你喜欢
  • 2013-01-03
  • 1970-01-01
  • 2015-02-08
  • 2011-07-18
  • 1970-01-01
  • 2017-12-16
  • 2017-05-22
  • 1970-01-01
  • 2011-11-07
相关资源
最近更新 更多