[英]Code execution throws error “object is not a function”
當我執行以下代碼時,出現以下錯誤。 未捕獲的TypeError:對象不是函數
<html>
<script>
var obj_1 = {x:1, y:2}
(function (o)
{
for(i in o)
{
console.log(i);
}
})(obj_1);
</script>
</html>
請解釋造成此錯誤的原因? 謝謝。
聲明后,您缺少分號。 它認為您正在嘗試調用{x:1, y:2}()
。 半冒號是可選的,通常可以使用,除非您有一些模棱兩可的地方。
這就是為什么您應該始終使用分號的原因;
您應該始終做的另一件事是不像在for
循環中那樣創建全局變量
// This works
var obj_1 = {x:1, y:2};
(function (o)
{
for(var i in o)
{
console.log(i);
}
})(obj_1);
當您不完成以下內容時;
,JavaScript首先會嘗試將下一行合並到該語句中,如果不能,那么就好像有一個;
。
// The following inserts a semi-colon because
// "var x = 2 x = 3" is not a valid statement
var x = 2
var x = 3
// The following does not insert a semi-colon because
// "var x = $().height(50).width(100);" is a valid statement
var x = $('p').
height(50).
width(100);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.