怎样在AssetManager.Bundle.Load回调方法里,调用脚本的类别变量

我写了一个脚本,继承于Component,有一个类别变量 public roles:Node[][];

实际测试发现在ts的规则下这种回调方法的this会是空值,而且load没有像on一样可以传一个变量作为this调用,那么在下面代码的function里我应该怎样才能读取类别变量this.roles?难道真的要宣告全局变量?

另外通过下面的印出,我发现element不为空值,index为空值,这是为何?element应该也是区域变量啊?load异议调用后forEach就结束了,实际上function被调用时element应该已经被销毁了才对

update(deltaTime: number) {

    if(this.monsterSetting!=undefined&&this.monsterMats!=undefined&&this.init==false){

        this.roles = new Array(4);

        for(let i=0;i<4;i++){

            this.roles[i] = new Array(3);

        }

        let index:number =0;

        this.StartPoints.forEach(element => {

            let newRole= instantiate(this.RolePrefab);

            newRole.setWorldPosition(element.node.position);

            newRole.setParent(director.getScene());

            this.roles[element.y][element.x]=newRole;

            this.monsterMats.load(this.monsterSetting[index++].IconPath,Material,function(err,mat){

                console.log("this.monsterMats.load mat:",mat);

                console.log("element:",element);

                console.log("newRole:",newRole);

                console.log("this:",this);

                let traget:Node =  this.roles[element.y][element.x];

                traget.getComponent<RoleControler>(RoleControler).Renderer.setMaterial(mat,0);

            })

           

            if(index>2){

                index=0;

            }

        });

        console.log("Stage start this.roles:",this.roles);

        console.log("all nodes:",director.getScene().children);

        this.init=true;

    }

}

前面会用箭头函数,后面就突然不会了?
不会的话,就把this提前赋值吧
当然,如果能把语法基础打好,会事半功倍
另外,update里面这样玩,会很卡的~

加个.bind(this)就行了吧。

可以,但是bind其实是创建了一个新的函数,有时候需要特别注意下。

建议复习下js或者ts语法