我在 Protractor 中有一个基本函数,写为:
this.getCurrentUrl = function () {
browser.getCurrentUrl().then(function(url){
console.log('url : '+url);
});
};
现在有没有一种方法可以访问内部函数作用域之外的“url”,因为我需要将此值返回给调用此函数的其他函数。我需要获取值并从 then(function(url){...}
外部返回它
最佳答案
url 将异步获取,因此您不能只分配它。您可能想给它一个回调。
function handleUrl(url) {
// here is where you do something with the url
}
// let your callback be called
this.getCurrentUrl = function(fn) {
browser.getCurrentUrl().then( function (url) {
fn(url);
})
}
// make the call with your handler
this.getCurrentUrl(handleUrl);
另一种方法是让你的函数返回一个“容器”,然后它会膨胀。然后你可以检查你的容器。由于该行为是异步的,因此您不知道它何时准备好,因此您可以按时间间隔或其他方式检查它......
// return a container object
this.getCurrentUrl = function() {
var urlContainer = {};
browser.getCurrentUrl().then( function (url) {
urlContainer.url = url;
});
return urlContainer;
}
var urlContainer = this.getCurrentUrl(); // starts off as an empty object
urlContainer.url // undefined
// then shortly in the future
urlContainer.url // has some url
第三种方法是返回闭包
this.getCurrentUrl = function() {
var urlValue;
browser.getCurrentUrl().then(function(url) {
urlValue = url;
});
return function() {
return urlValue;
}
}
var getUrl = this.getCurrentUrl();
getUrl(); // initially, returns undefined;
// keep trying. then shortly in the future...
getUrl(); // now has the url
关于javascript - javascript中如何扩展函数变量的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37338310/