Javascript 使用原型模式创建传单图:onEachFeature函数出错

Javascript 使用原型模式创建传单图:onEachFeature函数出错,javascript,leaflet,prototypal-inheritance,Javascript,Leaflet,Prototypal Inheritance,我调用以下代码来创建map的copy对象,并初始化传单map。这可以正常工作和加载。但是,onEachFeature和/或clickFeature功能无法正常工作 var map = { mapUrl: "", maxZoom: 18, minZoom: 2, map: L.map('worldMap').setView([51.505, -0.09], 2), create: function(values) { var instance

我调用以下代码来创建map的copy对象,并初始化传单map。这可以正常工作和加载。但是,onEachFeature和/或clickFeature功能无法正常工作

var map = {
    mapUrl: "",
    maxZoom: 18,
    minZoom: 2,
    map: L.map('worldMap').setView([51.505, -0.09], 2),
    create: function(values) {
        var instance = Object.create(this);
        Object.keys(values).forEach(function(key) {
        instance[key] = values[key];
        });
        return instance;
    },
    initLeafletMap: function() {
        L.tileLayer(this.mapUrl, {
            attribution: '',
            maxZoom: this.maxZoom,
            minZoom: this.minZoom,
            id: 'mapbox.streets'
        }).addTo(this.map);
        //add continents' outlines
        $.getJSON("/static/continents.json", 
           (function(style, onEachFeature, map) {
                return function(continents) {
                    console.log(typeof(continents));
                    L.geoJson(continents, {
                        style: style,
                        onEachFeature: onEachFeature
                    }).addTo(map);
                };
            }(this.style, this.onEachFeature, this.map))
       );
    },
    style: function() {
        return {
            weight: 2,
            opacity: 1,
            color: 'beige',
            dashArray: '3',
            fillOpacity: 0
        };
    },
    onEachFeature: function(feature, layer) {
        layer.on({
            click: this.clickFeature
        });
    },
    clickFeature: function(e) {
            do something here();
    },
因此,当我单击地图时,我知道调用了onEachFeature函数,但它不调用clickFeature。相反,我在控制台中遇到以下错误:

leaflet.js:5 Uncaught TypeError: Cannot read property 'call' of undefined
    at e.fire (leaflet.js:5)
    at e._fireDOMEvent (leaflet.js:5)
    at e._handleDOMEvent (leaflet.js:5)
    at HTMLDivElement.r (leaflet.js:5)

当您将
onEachFeature
方法作为iLife的参数传递以构建对AJAX调用的回调时,很可能只需要绑定
this
上下文:

this.onEachFeature.bind(this)
另见


顺便说一句,您也可以直接在传单GeoJSON层组上附加click事件侦听器,而不是为每个子层附加它。

当您将
onEachFeature
方法作为IIFE的参数传递到AJAX调用时,很可能只需绑定
上下文即可:

this.onEachFeature.bind(this)
另见


顺便说一句,您也可以直接将单击事件侦听器附加到传单GeoJSON层组上,而不是为每个子层附加。请使用未缩小的
传单src.js
文件,而不是
传单.js
-这将为您提供更可读的堆栈跟踪。请使用未缩小的
传单src.js
文件而不是
spoolet.js
——它将为您提供更可读的堆栈跟踪。