JavaScript OOP 函数引用尚未声明

JavaScript OOP function reference not yet declared

我又来解开另一个Javascript谜团了。

考虑这段代码:

starmap = function(game){

    this.PI2 = Math.PI * 2;
    this.renderer = {
      ...
    }
    
    this.star = function (...) {
      console.log(this.map);
      ...
    }
      
    this.map = {
      ...
    }
}
    
starmap.prototype = {

    preload: function(){},
    create : function(){
        this.map.initialize('starmap');
    },

    update: function(){
        
    }
}

map.initialize 调用 star 和 star 本身内部有对地图的引用,但我在开始时收到它未定义的错误。

现在我已经通过添加

解决了这个问题
var m = this.map

就在地图声明的下方,但这似乎有点古怪。 正确的做法是什么?

谢谢!

尝试将 "this" 分配给常规变量:

starmap = function(game){

    var self = this; //<----

    self.PI2 = Math.PI * 2;

然后将 this 的所有用法替换为 self。例如,self.map 而不是 this.map。在 Javascript 中使用 this 很棘手,因为它的值会根据您调用当前函数的方式而变化。