定义的静态方法未定义

Defined static method is undefined

我做了一个静态方法geocode()。但是当我调用它时出现错误:

Uncaught TypeError: undefined is not a function

我想不通我在这里做错了什么。

'use strict';

var gMap = (function (window, document, Gmap) {
    var gMap;

    Gmap.geocode({ 'address': 'Paris, France' }, function (results, status) {
        if (status !== Gmap.geocodeStatus.OK) {
            throw new Error('Geocode was unsuccessful: ' + status);
        }

        gMap = new Gmap(document.getElementById('map-canvas'), {
            center: results[0].geometry.location,
            zoom: 10
        });
    });

    return gMap;
}(window, document, Gmap));

function Gmap(element, options) {
    if (!(typeof window.google === 'object' && typeof window.google.maps === 'object')) {
        throw Error('The Google Maps JavaScript API v3 library is required.');
    }

    this.googleMap = new google.maps.Map(element, options);
    this.currentLocation = options.center;
    this.markers = [];
}

Gmap.geocode = function (geocoderRequest, callback) {
    googleGeocoder = new google.maps.Geocoder();

    googleGeocoder.geocode(geocoderRequest, function (results, status) {
        callback(results, status);
    });
};

反转你的代码。 将 Gmap 定义放在 var gMap = ...

上方

这是由于 function hoisting。您的代码中发生的事情是您的 function Gmap(...) 被提升到顶部并在 之前 您的 var gMap = ... 被解析,但是您的 Gmap.geocode 是在之后声明的您的 var gMap 声明因此此时不存在。

要解决此问题,只需声明 Gmap.geocode 以上 var gMap = ...:

Gmap.geocode = function ( ... ) { ... } ;

var gMap = ... ;