类中对象的奇怪问题(John Resig简单继承)

Weird issue with object within class(John Resig simple inheritence)

本文关键字:Resig John 简单 继承 问题 对象      更新时间:2023-09-26

这是小提琴

这个是

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

不过,我不知道如何解决它,因为它似乎并不是为了正确处理对象属性。