类中对象的奇怪问题(John Resig简单继承)
Weird issue with object within class(John Resig simple inheritence)
这是小提琴
这个是
http://jsfiddle.net/P72UR/
这个不是
http://jsfiddle.net/j86TA/1/
很抱歉,我包含了这么多代码,只是想让测试尽可能接近。
第二个是使用一个对象来保存x和y值。第一个不是。
这可能是一个函数绑定问题,但我不能完全确定。
我有这个代码:
(function createClouds() {
var Cloud = Class.extend({
size: 0,
alpha: 0,
x: 0,
y: 0,
pos: {
x: 0,
y: 0
},
init: function (x, y, size, alpha) {
this.x = x;
this.y = y;
this.size = size;
this.alpha = alpha;
console.log(this.x) // this prints a random number. all good
},
update: function (time) {
},
draw: function (ctx) {
ctx.fillStyle = 'rgba(255, 255, 255, ' + this.alpha + ')';
ctx.beginPath();
ctx.fillRect(this.x, this.y, this.size, this.size);
ctx.closePath();
ctx.fill();
}
});
sg.Cloud = Cloud;
})();
然后我在画布上用随机点创建这个对象。
for (var i = 0; i < 20; i++) {
var x = sg.util.getRandomInt(0, sg.currentGame.width);
var y = sg.util.getRandomInt(0, sg.currentGame.height - 260);
var size = sg.util.getRandomInt(20, 200);
var alpha = sg.util.getRandomNumber(.1, .6);
sg.createEntity(new sg.Cloud(x, y, size, alpha));
}
sg.createEntity将此实体添加到数组中;
然后我调用一个方法。
for (var i = 0; i < sg.entities.length; i++) {
sg.entities[i].draw(this.context);
}
这吸引了所有的实体。
以上操作很好。我得到随机分数。
如果我改变这个。
(function createClouds() {
var Cloud = Class.extend({
size: 0,
alpha: 0,
x: 0,
y: 0,
pos: {
x: 0,
y: 0
},
init: function (x, y, size, alpha) {
this.pos.x = x;
this.pos.y = y;
this.size = size;
this.alpha = alpha;
console.log(this.pos.x) //this prints a random number;
console.log(this.pos) //inspecting this object shows same points.
},
update: function (time) {
},
draw: function (ctx) {
ctx.fillStyle = 'rgba(255, 255, 255, ' + this.alpha + ')';
ctx.beginPath();
ctx.fillRect(this.pos.x, this.pos.y, this.size, this.size);
ctx.closePath();
ctx.fill();
}
});
sg.Cloud = Cloud;
})();
这是因为.extend()
对基对象进行了浅层复制,但.pos
是一个对象,因此复制它会导致对自身的更多引用,而不是新实例。
下面是一个小例子:
var a = { x: 0 }, b = a;
b.x = 4;
console.log(a.x); // prints 4
不过,我不知道如何解决它,因为它似乎并不是为了正确处理对象属性。
相关文章:
- 类中对象的奇怪问题(John Resig简单继承)
- 如何删除javascript对象(John Resig - Simple Inheritance)
- 具有 John Resig 简单类模式的静态变量
- 是John Resig的“Simple Javascript Inheritance”仍然OK
- AngularJS Syntax - John Papa's Bindable up-top Syntax is
- 如何访问John Resig's类在ajax回调中
- Resig Advanced Javascript p #43
- AngularJS风格指南-Todd Motto vs John Papa vs Minko Gechev
- 与John Resig's类语法
- 使用John Resig's”;简单JavaScript继承”;我如何从一个方法中调用一个超级方法加上额外的代码
- John Resig's的简单类实例化和“;使用严格的“;
- var prototype=new this();有人能解释一下John resig在他的类继承博客中使用的这句话吗
- 了解 Jon Resig 对部分应用程序的实现
- 使用John Resig Extend扩展数组
- John resig 39;的微模板框架在asp.net网页上抛出错误
- John Resig's不赞成使用Javascript继承片段
- 是我,还是John Resig'关于部分应用程序的流行博客文章不起作用
- 为什么在 John Resig 的 JavaScript 中需要第二个闭包
- 关于John Resig简单继承的属性的奇怪问题
- Is it reasonable to use John Resig's Processing.js?