![](/img/trans.png)
[英]How to access a property of an object of an array from a function scoped inside of that object
[英]How to access an object property from a callback function inside its method?
我正在定義此類:
function GMap(map, marker, geocoder) {
this.map = map;
this.marker = marker;
this.geocoder = geocoder;
this.setMarker = function(address) {
this.geocoder.geocode({'address' : address}, function(results, status) {
map.setCenter(results[0].geometry.location);
marker.setPosition(results[0].geometry.location);
});
}
}
如何通過回調函數訪問GMap的map
和marker
屬性?
非常感謝。
Function對象原型具有一個“ apply”方法,可用於在函數內設置“ this”的上下文。 檢查API /代碼中是否包含geocoder.code,許多庫都會通過一個額外的參數為您處理,例如:
this.someObj.someFn(params, callback, scope);
在someFn中,它將使用類似於以下的回調:
callback.apply(scope || window, [callbackArg1, callbackArg2]);
這將使“回調”內的“ this”上下文成為已作為“作用域”傳入的內容,或者如果未傳入任何內容,則“ this”將成為窗口的全局上下文。 一些javascript庫還提供了一種創建回調函數委托的方法,該方法可以確保始終以預期的作用域調用該函數,無論最終從何處調用該函數。 一個例子就是ExtJS的Function.createDelegate
如果您使用的庫沒有提供內置功能,則可以在回調閉包中創建本地變量以進行引用,即:
this.setMarker = function(address) {
var thisGMap = this;
this.geocoder.geocode({'address' : address}, function(results, status) {
thisGMap.map.setCenter(results[0].geometry.location);
thisGMap.marker.setPosition(results[0].geometry.location);
});
}
這是您要找的東西嗎?
function GMap(map, marker, geocoder) {
this.map = map;
this.marker = marker;
this.geocoder = geocoder;
var currentGMap = this; // private variable bound to GMap constructor scope
this.setMarker = function(address) {
this.geocoder.geocode({'address' : address}, function(results, status) {
// currentGMap is available (yay closures)
currentGMap.map.setCenter(results[0].geometry.location);
currentGMap.marker.setPosition(results[0].geometry.location);
});
}
}
注意:map和marker也通過閉包綁定,盡管我假設您希望在創建GMap實例后能夠更改map和marker屬性。
編輯:是的,我看到凱文在他的遮陽篷的最后一部分也向我遮陽。
如果您使用的是jQuery,則有一種稱為$.proxy()
的方法可用於更改上下文(將函數的“ this”設置為所需的任何值)。
this.setMarker = function(address) {
this.geocoder.geocode({'address' : address}, $.proxy(function(results, status) {
this.map.setCenter(results[0].geometry.location);
this.marker.setPosition(results[0].geometry.location);
}, this));
}
我猜它是谷歌地圖嗎? 您為什么要穿過地圖和標記物? 使它們成為全局變量(即:放置var map;
在所有函數的外部),那么您應該可以從任何地方訪問它們。
在函數內重用變量名也是一個壞主意。 如果首先將它們傳遞給函數,則它們將成為函數變量,因此在函數中定義地圖,標記和地理編碼器是沒有意義的,因為您已經可以使用地圖,標記和地理編碼器來訪問它們。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.