[英]Order of Evaluation in javascript
I am confused regarding the order of evaluation in javascript.我对 javascript 中的评估顺序感到困惑。 For ex, this is the code I have written例如,这是我写的代码
this.getTabUrl=function()
{
this.logToConsole("1"+"getTabUrl is called");
var myUrl
chrome.tabs.getSelected(null, function(tab)
{
myUrl = tab.url;
console.log("2"+tab.url);
console.log("3"+myUrl);
//this.parent.logToConsole(tabUrl);
});
this.tabUrl=myUrl;
this.logToConsole("3.1"+myUrl);
this.logToConsole("4"+this.tabUrl);
return myUrl;
}
When I call this function, this is the Output I get当我调用这个 function 时,这是我得到的 Output
> 1getTabUrl is called
> 3.1undefined
> 4undefined
> 2undefined
How come 3.1 and 4 is evaluated first before 2.为什么要先评估 3.1 和 4,然后再评估 2。
The function passed to chrome.tabs.getSelected()
is executed asynchronously.传递给chrome.tabs.getSelected()
的 function 是异步执行的。
You need to put everything that needs whatever gets passed to the callback inside the callback function.您需要将需要传递给回调的所有内容放在回调 function 中。 Note that this means you cannot return
a value from the outer function that relies on something from the callback.请注意,这意味着您不能从依赖于回调的某些内容的外部 function return
值。 You need to accept a callback argument instead and call it with the return value.您需要改为接受回调参数并使用返回值调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.