Javascript对象成员变量未克隆
Javascript object member variable not cloning
我正在从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
将引用新创建的实例。实例将不再使用x
、y
、text
和icon
的共享原型值。
附带说明:"我已经在使用0+来避免传递引用"——这不是必要的,因为基元类型总是被复制的。
相关文章:
- 替换另一个变量对象中的变量值
- 如何从表单变量对象中获取特定的from属性
- 变量/对象是否按值传递,为什么我不能在 javascript 中使用变量更改对象的属性
- 执行上下文和变量对象在 JavaScript 中实际上是一回事吗?
- 如何将变量对象传递到多个javascript弹出窗体
- 如何将javascript变量/对象从一个页面传递到另一个页面
- 在具有递增的变量/对象中存储和控制传单 GeoJSON 图层
- 在回调中重用变量/对象
- 给一个有1个变量/对象的函数给定几个参数
- 使用单词'英语'因为变量/对象名称在javascript中不起作用
- 如何访问变量对象中的数据
- 使用onclick调用变量对象中的函数
- 使用Underscore JS部分和for循环的未定义变量对象
- 如何查看我的变量对象
- 变量对象属性名称作为javascript中的参数
- 从变量对象中移除DOM元素,以便将其发布到服务器
- 根据变量对象是否等于“true”输出内容
- 如何连接(变量+对象键名)以获得点表示法的对象值
- 为什么在ES5中将变量对象改为词法环境
- 动态引用变量(对象)