简体   繁体   English

将变量从内部函数分配到外部作用域

[英]Assign variable from inner function to outer scope

I'm trying to make this code works, but I'm on the rocks with the functions scopes.我正在尝试使此代码正常工作,但我对函数范围感到困惑。

This is my code so far:到目前为止,这是我的代码:

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);
    });

} }

And this is the error I'm getting:这是我得到的错误:

Cannot read property 'add' of undefined

How can I assign the mesh I created in the inner function to the outer variable?如何将我在内部函数中创建的mesh分配给外部变量?

One solution is to put mesh in a variable defined in the function:一种解决方案是将网格放在函数中定义的变量中:

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);
});

Someone could write a book on how this works in javascript.有人可能会写一本关于如何this工程的JavaScript。 It's often not what you expect.这往往不是你所期望的。

Before loader.load() add在 loader.load() 之前添加

var that = this;

In your load function put在您的加载功能中放置

that.mesh.add(canoeMesh);

Problem is that "this" inside loader.load() points to somewhere else than outside of the function.问题是 loader.load() 中的“this”指向函数之外的其他地方。

I think you've got a couple options.我想你有几个选择。 One, is to assign this to another variable, like so:一,是分配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);
    });
}

Another option, if you have a transpiler, would be to use an arrow function, which retains lexical this :另一种选择,如果你有一个转译器,将使用一个箭头函数,它保留词法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);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM