Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

jquery - Why isn't this JavaScript syntax supported in Google Chrome?

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 )

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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");
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...