我正在尝试使用函数内联加载Google扩展。
下面是我页面中的<head>节中的链接。
<link rel="chrome-webstore-item"
href="https://chrome.google.com/webstore/detail/oafp--redacted--ffencd" />这是按钮。
<input type="button" class="btn btn-default" onclick="getExtension();">Go</input>这里是Javascript,它就出现在关闭的</body>标记之前。
<script type="text/javascript">
function getExtension() {
function extensionFailed(reason) {
console.log("extension Install Failed:", reason);
}
function extensionInstalled() {
console.log("installed");
};
console.log("calling install");
chrome.webstore.install(undefined, extensionInstalled(), extensionFailed());
console.log("install returned");
};
</script>单击调用getExtension的按钮将得到这一系列事件,一个接一个地传递。
chrome.webstore.install()之前)chrome.webstore.install()返回后)在其中的某个地方,异步地,我弹出了内联安装并接受它。
我以为..。
undefined。我肯定做错什么了。..。
发布于 2016-08-12 18:45:02
答案:
在这一行代码中:
chrome.webstore.install(undefined, extensionInstalled(), extensionFailed());
您实际上是通过在extensionInstalled()和extensionFailed()中使用extensionFailed()来执行函数的。如果要将它们作为回调传递,实际上可以像传递var那样传递函数本身。
chrome.webstore.install(undefined, extensionInstalled, extensionFailed);
作为变量的函数:
注释:--这不适用于您的代码,因为您在调用函数之前定义了它们,这是一个很好的实践。
您也可以将变量定义为函数,这只会使事情变得更加混乱。例如,这两个函数定义:
var myfunctionVar = function() {
console.log('hello, world');
}
function myfunction() {
console.log('hello, world');
}您可以正常地调用这些函数(即myfunctionVar()和myfunction())。
这两个定义之间的主要区别是,只有在定义本身被执行时,myfunctionVar才会变得可用,而在定义它的父函数的作用域中,myfunction是立即可用的(如果没有父函数,则执行脚本文件)。这是因为“吊装”,这只会使事情变得更复杂。
在本例中,您将无法在分配myfunctionVar()之前调用它。但是,调用myfunction()的情况并非如此,您可以在父函数中的任何地方调用它。
函数有点复杂(而且功能强大!)在Javascript比其他语言,所以希望这个答案为您澄清了一些事情。在这里,你可以从W3Schools上读到有关提升的内容。
https://stackoverflow.com/questions/38924474
复制相似问题