繁体   English   中英

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

[英]How to correctly pass “this” into function?

我努力使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;

this是之前和之后的功能正常访问,但我怎样才能让它通过? 就我而言, self也是不确定的。

通常有三种方法。 一种是在函数之前将其分配给另一个变量, this变量通常称为selfthat 变量将被捕获到函数的闭包中

let that = this;
geocoder.geocode(..., function(...) {
    that.isGeolocating
});

另一种方法是明确地告诉什么功能this是应该的,使用bind

geocoder.geocode(..., function(...) {
    this.isGeolocating
}.bind(this));

第三种是使用火箭功能 ,它不会重新分配this

geocoder.geocode(..., (...) => {
    this.isGeolocating
});

尝试这个:

let myBeautifulThis = this;
let geocoder = new google.maps.Geocoder;
geocoder.geocode({'location': geolocation}, function(results, status) {
  console.log('geolocation is ' + myBeautifulThis.isGeolocating);
});

您需要将this的引用存储在函数外部的变量中,或使用箭头函数。

所以要么

let self = this;
geocoder.geocode({'location': geolocation}, function(results, status) {
    // you existing code here
    // use self.isGeolocating
});

geocoder.geocode({'location': geolocation}, (results, status) => {
    // using this in here will use the this of the outer scope.
    // use this.isGeolocating
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM