[英]Typeof of a javascript function is defined before the function is declared?
Could somebody please explain or link to a resource that will tell me why : 有人可以解释一下或链接到一个告诉我原因的资源:
<script type=" type="text/javascript">
if(typeof window.myfunc == "function"){
alert("Why does myfunc already exist ?");
}
function myfunc(){
}
</script>
will pop up an alert while the myfunc function has not been defined yet ? 尚未定义myfunc函数时,是否会弹出警报?
I think I found an issue in Chrome, Safari and IE (not FF) which is linked to this behavior. 我认为我在Chrome,Safari和IE(不是FF)中发现了与此问题相关的问题。 It keeps me from extending the prototype of a function when the js file that contains the function is included more than once in a web page. 当包含该函数的js文件多次包含在网页中时,它使我无法扩展该函数的原型。 I'd like to know more about this before calling it a bug and reporting it. 在将其称为错误并报告之前,我想了解更多有关此的信息。
Thank you ! 谢谢 !
Named function declarations, including the function body, get hoisted to the top of the scope in JavaScript. 命名函数声明(包括函数主体)被提升到JavaScript范围的顶部。 I'd recommend reading this article about JavaScript scoping and hoisting . 我建议阅读这篇有关JavaScript作用域和提升的文章 。
If you did something like this, where you assigned the function to a named variable, only the variable declaration would be hoisted, but it wouldn't have a value until the assignment actually took place: 如果您执行了类似的操作,即在该函数中将函数分配给了一个命名变量,则只会悬挂该变量声明,但在赋值实际发生之前它没有值:
if (typeof myFunc == 'function') {
// will not be reached
}
var myFunc = function() { ... }
The above effectively gets treated as: 以上有效地被视为:
var myFunc; // myFunc is undefined
if (typeof myFunc == 'function') {
// will not be reached
}
myFunc = function() { ... }
One word: hoisting 一句话: 吊装
A quote from JavaScript Garden: JavaScript Garden的一句话:
"The above function gets hoisted before the execution of the program starts; thus, it is available everywhere in the scope it was defined in, even if called before the actual definition in the source ." “上面的函数在程序开始执行之前就已被吊起;因此,即使在源中的实际定义之前调用了它,它在定义它的范围中的任何地方都可用 。”
More info here: http://bonsaiden.github.com/JavaScript-Garden/#function.general 此处提供更多信息: http : //bonsaiden.github.com/JavaScript-Garden/#function.general
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.