语法:
('参数')=>{ '函数执行的内容' }
简化了函数的命名
var test = function(){ }
<=等同于=> var test = ()=>{ } () => { … } // 零个参数用 () 表示; x => { … } // 一个参数可以省略 (); (x, y) => { … } // 多参数不能省略 ();
箭头函数内部没有constructor方法,也没有prototype,所以不支持new操作。但是它对this的处理与一般的普通函数不一样。箭头函数的 this 始终指向函数定义时的 this,而非执行时
// 带返回值 var test = function(x,y){ return t ; } var test = (x,y)=>{ return x+y; } //不带返回值 $('#test').click(function(event){ event.stopPropagation();//阻止冒泡 }); $('#test').click((event)=>{ event.stopPropagation();//阻止冒泡 })特性[1,2,3].map(function(x){ return x*x; }); 等同于 [1,2,3].map(x => x*x);
var o = { x : 1, func : function() { console.log(this.x) }, test : function() { setTimeout(function() { this.func(); }, 100); } }; o.test(); // TypeError : this.func is not a function
var o = { x : 1, func : function() { console.log(this.x) }, test : function() { setTimeout(() => { this.func() }, 100); } }; o.test();