Javascript向google.maps.Map添加函数

Javascript adding functions to google.maps.Map

本文关键字:添加 函数 Map maps google Javascript      更新时间:2023-09-26

我在向google.maps.Map对象添加两个函数(一个调用另一个)时遇到了一些困难

google.maps.Map.prototype.addMarkerFromJson = function() {
    alert("hi");
}
google.maps.Map.prototype.getPictureDataFromJson = function (jsonObj) {
    this.addMarkerFromJson();
}

此代码引发错误:

Uncaught TypeError: Object #<Object> has no method 'addMarkerFromJson'

这本身就令人困惑,更让我困惑的是当我更改名称时:

google.maps.Map.prototype.anotherTestFunction = function() {
    alert("hi");
}
google.maps.Map.prototype.aTestFunction = function (jsonObj) {
    this.anotherTestFunction();
}

这仍然不起作用(警报不会被触发),但它也不会在控制台中引发错误?

我很想知道我到底做错了什么,以及对邪恶的解释!

编辑:当我再次看到它时,我开始认为this.addMarkerFromJson();中的this实际上指的是function()定义,而不是我将其附加到的Map对象?在这种情况下,我该如何调用另一个函数?

回答我自己的问题:

这是我的愚蠢!我使用mapObject.getPictureDataFromJson()作为jquery.get()的成功回调,因此this引用了调用方(get函数)而不是映射对象。