[英]Javascript object member variable not cloning
I'm inheriting an object from the EASELJS library. 我正在从EASELJS库继承一个对象。 To simplify the problem, I'm reducing the code into the minimal form.
为了简化问题,我将代码简化为最小形式。
I have a class: 我有一堂课:
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;
})();
Then I use it in another js object: 然后在另一个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
The config file: 配置文件:
var _profileselConfig = function(){
this.cancelx = 0;
this.cancely = 240;
};
profileselConfig = new _profileselConfig();
And what am i doing wrong? 我在做什么错呢?
I'm already using 0 + to avoid passing the reference and it's not working. 我已经在使用0 +以避免通过引用,并且它不起作用。 What should I do now?
我现在应该怎么办? Any suggestions?
有什么建议么? Thanks.
谢谢。
You should probably be calling this.init
rather than p.init
in your constructor. 您可能应该在构造函数中调用
this.init
而不是p.init
。
When you call p.init
, the this
inside of init
refers to the prototype. 当您调用
p.init
, init
的this
就是原型。 Thus, whenever you create an instance, your p.init
call modifies the prototype for all _jsbutton
objects. 因此,无论何时创建实例,您的
p.init
调用都会修改所有 _jsbutton
对象的原型。
That's why both buttons have the same x/y values: they both get their position from the same prototype, and the last-run constructor set the prototype values. 这就是两个按钮都具有相同x / y值的原因:它们都从同一原型获得其位置,最后运行的构造函数设置了原型值。 When you set
buttoncancel2.y
outside of the constructor, you gave that instance its own y
property, so it no longer used the shared prototype value. 在构造函数外部设置
buttoncancel2.y
,您为该实例提供了自己的y
属性,因此该实例不再使用共享原型值。
If you call this.init
in your constructor, then the this
in init
will refer to your newly-created instance. 如果你打电话
this.init
在你的构造,那么this
在init
会参考您的新创建的实例。 The instances will no longer use the shared prototype values for x
, y
, text
, and icon
. 实例将不再使用
x
, y
, text
和icon
的共享原型值。
Side note: " I'm already using 0 + to avoid passing the reference " -- this is not necessary, because primitive types are always copied. 旁注:“ 我已经在使用0 +以避免传递引用了 ”-这不是必需的,因为原始类型总是被复制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.