Google Chrome为什么不支持这种JavaScript语法? [英] Why isn't this JavaScript syntax supported in Google Chrome?

查看:200
本文介绍了Google Chrome为什么不支持这种JavaScript语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这段代码在Firefox中工作得很好,但在Chrome中,这似乎给我一个语法错误。
为什么是这样,因为这对我来说看起来像'ok'语法。



您可以通过执行

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

在Firefox 27.0.1中,返回0
在Chrome中返回 SyntaxError:Unexpected token)

解决方案

胖箭头 ES6的一项功能(现在正式称为ECMAScript 2015)。它已在Firefox中引入,但尚未在其他浏览器中引入(特别是不完全在V8中这对于nodejs / iojs开发来说会很有趣)。

因为它主要是糖,所以最好在使用之前等一下。



如果您需要范围绑定(这个)在函数调用和函数定义范围中是相同的,我们说的是lexical this),然后而不是

  $(#test)。on(click ,()=> {
某些代码
});

您可以简单地做

($$ test)。on(click,(function(){
some code
})。bind(this));

如果你没有(如你的例子),那么简单地做

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


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 )

解决方案

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

这篇关于Google Chrome为什么不支持这种JavaScript语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆