Why isn't this JavaScript syntax supported in

2019-01-25 07:48发布

问题:

I initiated a JavaScript/jQuery click listener like this:

$("#test").on("click", () => {
   console.log("test");
});

This piece of code works perfectly fine in Firefox but in Chrome this seems to give me a Syntax error. Why is this, since this looks like 'ok' syntax to me.

You can test this quickly in the console by doing

 var a = () => {return 0;}
 a();

In Firefox 27.0.1 this returns 0 In Chrome it returns SyntaxError: Unexpected token )

回答1:

The fat arrow is a feature of ES6 (now officially called ECMAScript 2015). It's been introduced in Firefox but not yet in other browsers (and especially not completely in V8 which would be interesting for nodejs/iojs development).

As it's mostly sugar, you'd better wait before using it.

If you need the scope binding (this is the same in the function call and in the scope in which the function was defined, we speak of "lexical this"), then instead of

$("#test").on("click", () => {
   some code
});

you can simply do

$("#test").on("click", (function() {
   some code
}).bind(this));

If you don't (as in your example), then simply do

$("#test").on("click", function() {
   console.log("test");
});