如何从其方法内的回调函数访问对象属性?

Tot*_*oto 0 javascript

我正在定义这个类:

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);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

你怎么能访问map和marker从回调函数GMAP的属性?

非常感谢.

Kev*_*han 5

Function对象原型有一个"apply"方法,您可以使用该方法在函数中设置"this"的上下文.检查任何geocoder.code的API /代码,许多库将通过一个额外的参数为您处理这个,即:

this.someObj.someFn(params, callback, scope);
Run Code Online (Sandbox Code Playgroud)

在someFn中,它将使用与此类似的回调:

callback.apply(scope || window, [callbackArg1, callbackArg2]);
Run Code Online (Sandbox Code Playgroud)

这将使"回调"中的"this"上下文作为"范围"传递,或者如果没有传入任何内容,则"this"将是窗口的全局上下文.一些javascript库还提供了一种创建回调函数委托的方法,该委托确保始终使用预期范围调用函数,无论它最终从何处被调用.这方面的一个例子是ExtJS的Function.createDelegate

如果您使用的库不提供内置功能,那么您可以在回调闭包中创建一个本地var引用,即:

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);
    });
}
Run Code Online (Sandbox Code Playgroud)