简体   繁体   中英

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

    <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}() . 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

// 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 ; .

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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