我如何在子javascript代码中使用父变量?

时间:2012-12-10 22:34:42

标签: javascript three.js

这段代码在子节点中使用继承我在父节点中声明的场景中添加了一些东西我怎么做它在子级别看场景中得到错误

 function parent    (domElement, renderStatistics) {
    this.scene = new THREE.Scene();
    }
function child(domElement) {
    parent.call(this, domElement);
    this.init();
}
child.prototype = Object.create(parent.prototype);

child.prototype.constructor = Young;


child.prototype.init = function () {
function createLab(geometry) {
        var mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial());
        this.scene.add(mesh);  // this error Cannot call method 'add' of undefined
    }
}

3 个答案:

答案 0 :(得分:2)

child.prototype.init = function () {
var _this = this;
    function createLab(geometry) {
        var mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial());
        _this.scene.add(mesh);  
    }
}

答案 1 :(得分:1)

看起来你的错误原因是第二行的双等于= =

这会导致值的归属为布尔值,而不是您期望的新THREE.Mesh的实例。

答案 2 :(得分:0)

我不确定为什么你需要在init ...

中创建内部函数

尝试

child.prototype.init = function () {
        var mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial());
        this.scene.add(mesh);  // this error Cannot call method 'add' of undefined
}

或者

function createLab(geometry) {
    var mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial());
    this.scene.add(mesh);  // this error Cannot call method 'add' of undefined
 };

child.prototype.init = function () {
     createLab.call(this, whatever);
}