[英]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
变量通常称为self
或that
。 变量将被捕获到函数的闭包中 。
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.