javascript - "this"的正确 JavaScript 使用

标签 javascript json

以下两种调用 Color 属性的方法哪一种更好?为什么?或者说有什么区别吗?

lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},

或者

lineSymbolizer:{strokeColor: LatLongLines.Color, strokeWidth: 2, strokeOpacity: 0.7},

上下文代码:

var LatLongLines = {
    Graticule: null,
    Color: "#000000",
    Show: function () {
        this.Graticule.activate();
    },
    Hide: function () {
        this.Graticule.deactivate()
    },
    Initialize: function () {
        this.Graticule = new OpenLayers.Control.Graticule({
            numPoints: 2,
            labelled: true,
            lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},
            labelSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7}
        });

        map.addControl(this.Graticule);
    }
};

最佳答案

就我个人而言,我可能会坚持使用 this.Color。如果您这样做,那么当您决定有一天克隆“LatLongLines”对象时,一切都会继续进行。

this 的道非常复杂,但在这种情况下,它将是通过“通过”“LatLongLines”引用调用函数而绑定(bind)的上下文对象。如果这些函数可能偏离原始对象,则必须采取措施保留上下文对象的内存,以便在调用时它是正确的,但这在您发布的任何内容中都不明显。

关于javascript - "this"的正确 JavaScript 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4440717/

相关文章:

javascript - NextJS路由: why do there need to be different client and server routes?

javascript - 将变量传递给另一个模块

javascript - CSS3 是否使用 JavaScript?

javascript - 如何使用 JavaScript 变量提取 JSON 字符串?

javascript - 下载 json 文件并将其导入到您的 firebase 数据库

javascript - 类型错误 : Cannot read property 'upvote' of undefined in mean stack

javascript - 搜索从 api 调用返回的 json

javascript - D3.js - 来自平面 JSON 层次结构的 TreeMap

c# - 按名称/键在 JArray 中查找项目

javascript - 如何使用 JQuery 根据屏幕尺寸实时更新 CSS?