简体   繁体   English

代码执行抛出错误“对象不是函数”

[英]Code execution throws error “object is not a function”

When i execute the below code i get the below error. 当我执行以下代码时,出现以下错误。 uncaught TypeError: 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>

Please explain what causes this error? 请解释造成此错误的原因? Thanks. 谢谢。

You're missing a semi-colon after your declaration. 声明后,您缺少分号。 It thinks you're trying to call {x:1, y:2}() . 它认为您正在尝试调用{x:1, y:2}() Semi colons are optional and usually work, unless you have something ambiguous as you do. 半冒号是可选的,通常可以使用,除非您有一些模棱两可的地方。

That is why you should always use semi-colons; 这就是为什么您应该始终使用分号的原因;

Another thing you should always do is not create global variables as you are in your for loop 您应该始终做的另一件事是不像在for循环中那样创建全局变量

// This works
var obj_1 = {x:1, y:2};
(function (o)
{
    for(var i in o)
    {
    console.log(i);
    }
})(obj_1);

When you don't finish a line with ; 当您不完成以下内容时; , JavaScript will first try to incorporate the next line into the statement, if it can't, then it acts as if there were a ; ,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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM