从内部函数到外部作用的变量变量

时间:2017-10-22 15:10:45

标签: javascript three.js

我正在尝试使这段代码正常工作,但我的功能范围很突出。

到目前为止,这是我的代码:

var Canoe = function () {
    this.mesh = new THREE.Object3D();
    var loader = new THREE.JSONLoader();
    loader.load( 'models/canoe.json', function ( geometry, materials ) {
        var canoeMesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ));
        canoeMesh.castShadow = true;
        canoeMesh.receiveShadow = true;
        this.mesh.add(canoeMesh);
    });

}

这就是我得到的错误:

Cannot read property 'add' of undefined

如何将我在内部函数中创建的mesh分配给外部变量?

3 个答案:

答案 0 :(得分:2)

一种解决方案是将网格放入函数中定义的变量中:

var Canoe = function () {
var mesh = new THREE.Object3D();
this.mesh = mesh;
var loader = new THREE.JSONLoader();
loader.load( 'models/canoe.json', function ( geometry, materials ) {
    var canoeMesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ));
    canoeMesh.castShadow = true;
    canoeMesh.receiveShadow = true;
    mesh.add(canoeMesh);
});

有人可以写一本关于this如何在javascript中运行的书。这通常不是你所期望的。

答案 1 :(得分:0)

在loader.load()之前添加

var that = this;

在你的加载函数中

that.mesh.add(canoeMesh);

问题是loader.load()中的“this”指向除函数外部以外的其他地方。

答案 2 :(得分:0)

我认为你有几个选择。一,是将this分配给另一个变量,如下所示:

var self = this;
var Canoe = function () {
    self.mesh = new THREE.Object3D();
    var loader = new THREE.JSONLoader();
    loader.load( 'models/canoe.json', function ( geometry, materials ) {
        var canoeMesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ));
        canoeMesh.castShadow = true;
        canoeMesh.receiveShadow = true;
        self.mesh.add(canoeMesh);
    });
}

另一个选择,如果你有一个转换器,将使用一个箭头函数,它保留词汇this

var Canoe = () => {
    this.mesh = new THREE.Object3D();
    var loader = new THREE.JSONLoader();
    loader.load( 'models/canoe.json', function ( geometry, materials ) {
        var canoeMesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ));
        canoeMesh.castShadow = true;
        canoeMesh.receiveShadow = true;
        this.mesh.add(canoeMesh);
    });
}