Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...