如何在对象的方法内部访问正确的对象

时间:2019-03-27 13:45:57

标签: javascript this

我有一个事件处理程序,它调用selectContinents()函数:

var map = {
    eventHandler: function() {
        events.on('continentsChangedDropdown', (continents) => this.selectContinents(continents));
    },
    selectFeature: function(layer) {
            //selects feature;
    },
    unselectFeature: function(layer) {
            //unselects feature;
    },
    selectContinents: function(continents) {
        geojson.eachLayer(function(layer) {
            var continent = layer.feature.properties.continent;
            if (continents.includes(continent)) {
                this.selectFeature.bind(this, layer);
            }
            else {
                this.unselectFeature.bind(this, layer);
            }
        });
    }
};

依次调用selectFeature()unselectFeature()

但是返回

map.js:105 Uncaught TypeError: Cannot read property 'bind' of undefined

我理解bind(this)中的这一点并不涉及地图对象,但我不知道如何访问地图对象。

1 个答案:

答案 0 :(得分:0)

改为使用箭头功能。它们保留了封闭范围:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

geojson.eachLayer((layer) => {
    var continent = layer.feature.properties.continent;
        if (continents.includes(continent)) {
            this.selectFeature.bind(this, layer);
        }
        else {
            this.unselectFeature.bind(this, layer);
        }
    });