ES6 箭头函数(=>)

来源:互联网 发布:java岗位管理制度 编辑:程序博客网 时间:2024/06/05 06:02

语法:

('参数')=>{    '函数执行的内容'}
简化了函数的命名
var test = function(){} 
<=等同于=>var test = ()=>{}() => { … } // 零个参数用 () 表示;    x => { … } // 一个参数可以省略 ()(x, y) => { … } // 多参数不能省略 ()

// 带返回值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);

特性
箭头函数内部没有constructor方法,也没有prototype,所以不支持new操作。但是它对this的处理与一般的普通函数不一样。箭头函数的 this 始终指向函数定义时的 this,而非执行时


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();


1 0