问题:当继承对象的属性和方法时,子对象似乎与父对象的连接松散,这就是'。为了更好地说明它,请看我的例子:
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(...);
答案 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 = ...
}