如何正确地将"this"传递给函数?

Chr*_*ris 1 javascript

我努力this进入我的功能,如下所示:

console.log('geolocation is ' + this.isGeolocating);

let geocoder = new google.maps.Geocoder;
geocoder.geocode({'location': geolocation}, function(results, status, self = this) {
    console.log('geolocation is ' + self.isGeolocating);
    if (status === 'OK') {
        if (results[0]) {
            console.log(results[0]);
            self.geolocated = 'success';
        } else {
            // No results found
            self.geolocated = 'error';
        }
    } else {
        console.log('Geocoder failed due to: ' + status);
        self.geolocated = 'error';
    }
});

this.isGeolocating = false;
Run Code Online (Sandbox Code Playgroud)

this在函数之前和之后可以正确访问,但是如何通过它?self在我的情况下也是未定义的.

Ama*_*dan 7

通常有三种方法.一种是在函数之前分配this给另一个常规名称self或变量的变量that; 变量将被捕获到函数的闭包中.

let that = this;
geocoder.geocode(..., function(...) {
    that.isGeolocating
});
Run Code Online (Sandbox Code Playgroud)

另一个是明确告诉函数this应该是什么,使用bind:

geocoder.geocode(..., function(...) {
    this.isGeolocating
}.bind(this));
Run Code Online (Sandbox Code Playgroud)

第三个是使用火箭功能,不重新分配this:

geocoder.geocode(..., (...) => {
    this.isGeolocating
});
Run Code Online (Sandbox Code Playgroud)