Javascript对象成员变量未克隆

Javascript object member variable not cloning

本文关键字:变量 对象 成员 Javascript      更新时间:2023-09-26

我正在从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+来避免传递引用,但它不起作用。我现在该怎么办?有什么建议吗?谢谢

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

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

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

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

附带说明:"我已经在使用0+来避免传递引用"——这不是必要的,因为基元类型总是被复制的。