App-contextual 风格函数 (OpenLayers 4)

App-contextual style function (OpenLayers 4)

我正在尝试找出一种方法 具有应用程序上下文样式函数 用于绘图交互 (OpenLayers 4)。

我有一个用自定义样式函数构造的 Draw Interaction(我的一个对象的原型方法),但问题是该函数将用 this 调用为Window,所以我无法访问我的应用上下文。

因为我不负责那个调用(由 OpenLayers 调用),所以我无法指定我想要的 this

是否有我在 OpenLayer API 或 javascript(我不是专家)中没有看到的细节可以解决我的问题?

这是我的代码:

function MyClass(){
    (...)

    // This state should impact the draw interaction style
    this.myState = someValue;

    // My interaction
    this.addInteraction = new ol.interaction.Draw({
        (...)
        style: this.styleFunction
    });
}

// My style function which need to access this.myState
MyClass.prototype.styleFunction = function( feature, resolution ) {

    // The following this is Window instead of MyClass.this
    if( this.myState )
        return style1;
    else
        return style2;
}

添加 MyClass.this 作为 Window 属性 不是解决方案,因为我可能有多个 MyClass 实例。

感谢任何建议

我终于找到了解决办法:

Function.prototype.bind() 方法可以完成准确的工作。在给交互赋予样式功能时使用它:

style: this.styleFunction.bind(this)

更多信息:Documentation