Вопрос

I'm trying to write a simple AI for a game in JavaScript. (The game is not mine.) Here is the extent of my code so far for the AI:

function AIManager(grid) {
  this.events = {};
  this.grid = grid;

  setInterval(new function(){console.log("hello")}, 1000);
}

When I try to run the game, the console outputs "hello" a single time followed by

Uncaught SyntaxError: Unexpected identifier

once per second, with no stack trace or line number attached to it. (When I set the interval to 1 ms instead of 1000 ms, this error printed every 1 ms, so it is definitely responding to the setInterval function.)

Could anyone help me understand why this is happening? I'm a bit of a javascript noob right now... Thanks!

Это было полезно?

Решение

There's no need for the new in this case.

setInterval() is expecting a Function, which the function expression will already create.

setInterval(function(){console.log("hello")}, 1000);
// logs 'hello'
// logs 'hello'
// ...

The "hello" is logged once with new because it's invoking the Function immediately as a constructor.

var o = new function () {
    console.log("hello");
};
// logs "hello" during construction

console.log(typeof o); // "object"

And, the SyntaxError is likely because setInterval(), finding the argument isn't a Function, is converting the instance Object to a String that it can evaluate:

setInterval(new function () {
    this.toString = function () {
        return "console.log('foo');";
    };
}, 1000);
// logs 'foo'
// logs 'foo'
// ...

Note: Since timers (setTimeout() and setInterval()) aren't actually standardized, the behavior in the previous snippet may not be consistent between engines.

Другие советы

The unexpected identifier is {}.

The result of the expression

new function() { console.log("hello"); }

is an empty object ({}) which you can verify that in your console. That empty object is then being passed into setInterval as the first argument:

setInterval({}, 1000);

setInterval expects either a string or a function, not an object. So, since {} isn't a function it's passing it into the Function constructor in an attempt to get a function that it can execute, a la:

new Function({})

The result of that statement is your uncaught SyntaxError.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top