继承和“TypeError:无法读取未定义的属性'someProperty'”

时间:2014-05-25 08:02:58

标签: javascript

问题:当继承对象的属性和方法时,子对象似乎与父对象的连接松散,这就是'。为了更好地说明它,请看我的例子:

function RigidBody() {
    this.local = new Matrix4x3();
    this.position = new vec3();
    ...
}

RigidBody.prototype = {
    ...
    setPosition: function(vec) {
        this.position.copy(vec);
        this.local.setTranslation(this.position);
    }
    ...
};

CameraObject.prototype = new RigidBody();
CameraObject.prototype.constructor = CameraObject;

function CameraObject() {
    this.fov = ...
}

CameraObject.prototype.add = ...;

var camera = new CameraObject();
camera.add(...); // Works fine;
camera.setTranslation(...); // Throws "TypeError: Cannot read property 'setTranslation' of undefined
// And on another PC it throws: "http://localhost:8080/js/rigidBody.js(61): Uncaught exception: TypeError: Cannot convert 'this.local' to object"

如何绕过它?通过将this.this = this;分配给父对象并将其替换为this.this,我找到了解决此问题的方法。不幸的是,我需要将.this添加到每个相机函数调用中:camera.this.setPosition(...);

2 个答案:

答案 0 :(得分:0)

作为一般建议,请在您的代码中添加console.log(camera)并在一个好的浏览器控制台中检查该对象,我强烈推荐Firebug

通过这种方式,您可以探索camera对象

可用的属性和嵌套属性


来自原始问题中的代码示例,setTranslation似乎是camera.local的属性,而不是camera本身。

或者您可能想要将camera.setPosition(...);添加到RigidBody的原型,但之后从未使用过jsfiddle


并给出以下评论中提供的代码:

function Matrix4x3(){
    this.element = new Float32Array(16);
}

没有定义setTranslation,因此this.local.setTranslation也可能未定义..

答案 1 :(得分:-1)

你需要调用" super",换句话说,从父构造函数继承属性:

function CameraObject() {
    RigidBody.call(this); // inherit RigidBody properties
    this.fov = ...
}
相关问题