我很难将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
也是未定义的。
答案 0 :(得分:7)
通常有三种方法。一种方法是在函数之前将self
分配给另一个变量,通常命名为that
或let that = this;
geocoder.geocode(..., function(...) {
that.isGeolocating
});
;变量将被捕获到函数的closure。
this
另一种方法是使用bind
明确告诉函数geocoder.geocode(..., function(...) {
this.isGeolocating
}.bind(this));
应该是什么:
this
第三个是使用rocket function,但不会重新分配geocoder.geocode(..., (...) => {
this.isGeolocating
});
:
this
答案 1 :(得分:3)
试试这个:
let myBeautifulThis = this;
let geocoder = new google.maps.Geocoder;
geocoder.geocode({'location': geolocation}, function(results, status) {
console.log('geolocation is ' + myBeautifulThis.isGeolocating);
});
答案 2 :(得分:2)
您需要在函数外部的变量中存储对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
});
只是
from selenium import webdriver
driver = webdriver.Chrome("E:\Tutorial\Driver\chromedriver.exe")
words = ['girl', 'cat', 'dog', 'bird', 'man']
for word in words:
driver.get("https://translate.google.com.eg/?hl=en&tab=wT#en/fr/" + word)
translations = driver.find_elements_by_class_name('gt-baf-word-clickable')
for text in translations:
print(text.text)