Javascript:继承的对象更改反映到父级

时间:2014-06-23 22:48:11

标签: javascript

我的游戏有这个代码(还有更多,但这是重要的部分):

function BaseGameObject() {}
BaseGameObject.prototype.geometry = {
    shape: 'none'
};
BaseGameObject.prototype.type = null;
BaseGameObject.prototype.texture = 'black';

function GameObject(x, y) {
    this.geometry.x = x;
    this.geometry.y = y;
}
GameObject.inheritsFrom(BaseGameObject);

function Rectangle(x, y, width, height) {//todo solve reverse inheritance in geometry bject
    this.geometry.x = x;
    this.geometry.y = y;
    this.geometry.w = width;
    this.geometry.h = height;
}
Rectangle.inheritsFrom(GameObject);
Rectangle.prototype.geometry.shape = 'rectangle';

function Square(x, y, size) {
    this.geometry.x = x;
    this.geometry.y = y;
    this.geometry.w = size;
    this.geometry.h = size;
}
Square.inheritsFrom(Rectangle);

InheritsFrom看起来像这样:

Function.prototype.inheritsFrom = function (parentClassOrObject) {
    if (parentClassOrObject.constructor == Function) {
        //Normal Inheritance
        this.prototype = new parentClassOrObject;
        this.prototype.constructor = this;
        this.prototype.parent = parentClassOrObject.prototype;
    } else {
        //Pure Virtual Inheritance
        this.prototype = parentClassOrObject;
        this.prototype.constructor = this;
        this.prototype.parent = parentClassOrObject;
    }
    return this;
};

我的问题是,当我执行new Square(10, 500, 20)时,即使对于BaseGameObject原型,几何对象也会被更改,因为该对象存储为参考。

我的问题是,我可以以某种方式为每个对象设置单独的几何对象,从父原型继承几何对象,但更改不会反过来吗?

2 个答案:

答案 0 :(得分:0)

看看this question。虽然大多数答案都依赖于jQuery,但您可能会发现这样的内容很有用:

var defaults = { 'fo': 'bar' };
var clone    = JSON.parse( JSON.stringify( defaults ) );

这是@heinob's answer

答案 1 :(得分:0)

  

我可以以某种方式为每个对象分别设置几何对象,从父原型继承几何对象

是:

Function.prototype.inheritsFrom = function (parentClassOrObject) {
    if (parentClassOrObject instanceof Function) {
        parentClassOrObject = parentClassOrObject.prototype;
    }
    // Proper Inheritance
    this.prototype = Object.create(parentClassOrObject);
    this.prototype.constructor = this;
    this.prototype.parent = parentClassOrObject;
    return this;
};

function BaseGameObject() {
    // create own property with new object
    this.geometry = Object.create(this.geometry);
}
BaseGameObject.prototype.geometry = {
    shape: 'none'
};
BaseGameObject.prototype.type = null;
BaseGameObject.prototype.texture = 'black';

function GameObject(x, y) {
    BaseGameObject.call(this);
    this.geometry.x = x;
    this.geometry.y = y;
}
GameObject.inheritsFrom(BaseGameObject);

function Rectangle(x, y, width, height) {
    GameObject.call(this, x, y);
    this.geometry.w = width;
    this.geometry.h = height;
}
Rectangle.inheritsFrom(GameObject);
Rectangle.prototype.geometry = Object.create(BaseGameObject.prototype.geometry);
Rectangle.prototype.geometry.shape = 'rectangle';

function Square(x, y, size) {
    Rectangle.call(this, x, y, size, size);
}
Square.inheritsFrom(Rectangle);