构造函数中的变量集在不同的方法中是未定义的

时间:2015-04-23 13:27:22

标签: coffeescript

我正在使用Google地图计算票价,在CoffeeScript中创建一个库。

初始化地图时如下:

var viewport = document.getElementById('viewport'),
    options = {
        center: new google.maps.LatLng(-34.397, 150.644),
        zoom: 8
    };

google.maps.event.addDomListener(window, 'load', function()
{
    var map = new google.maps.Map(viewport, options);
});

按预期加载。

但是当我使用我的库初始化它时:

var viewport = document.getElementById('viewport'),
    options = {
        center: new google.maps.LatLng(-34.397, 150.644),
        zoom: 8
    },

    map = new FareJS.Map(viewport, options);

视口保持灰色,移动地图会显示TypeError: a is undefined

经过一番研究后,我发现@opt类中方法initializeMapMap的值未定义。我发现这很奇怪,因为我在构造函数中设置它。陌生人仍然是@viewport 未定义...只是@opt

有问题的课程是

class Map
    constructor: (@viewport, @opt) ->
        if not window.hasOwnProperty('google')
            throw "Google Maps API could not be found, are you sure you installed it?"

        @loadMapOnLoad()

    initializeMap: () ->
        @map = new google.maps.Map(@viewport, @opt)
        return

    loadMapOnLoad: () ->
        google.maps.event.addDomListener(window, 'load', @initializeMap)
        return

编译的内容如下:

var Map;

Map = (function() {
    function Map(viewport, opt) {
        this.viewport = viewport;
        this.opt = opt;
        if (!window.hasOwnProperty('google')) {
            throw "Google Maps API could not be found, are you sure you installed it?";
        } 
        this.loadMapOnLoad();
    }

    Map.prototype.initializeMap = function() {
        this.map = new google.maps.Map(this.viewport, this.opt);
    };

    Map.prototype.loadMapOnLoad = function() {
        google.maps.event.addDomListener(window, 'load', this.initializeMap);
    };

    return Map;

})();

为什么要这样做以及如何解决?

1 个答案:

答案 0 :(得分:3)

问题是initializeMap将在您的类/对象的上下文之外执行。 this不会引用initializeMap中的类实例。您必须执行以下操作之一:

# explicitly bind to @
# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
google.maps.event.addDomListener window, 'load', @initializeMap.bind @

# preserve context with => and call regularly 
google.maps.event.addDomListener window, 'load', => @initializeMap()

# declare method with bound context, so it doesn't matter how you call it
# (resulting behaviour could be considered somewhat unidiomatic for JS, caveat emptor)
class Map
  initializeMap: =>
    ..