es6 箭头函数

var f = v=> v;
等同于
var f = function f(v) {
  return v;
};
var f = ()=> 5
==
var f = function f() {
  return 5;
};
var sum = (a, b) => a + b;
==
var sum = function sum(a, b) {
  return a + b;
};
//返回对象必须加上()
var getObj = ()=>({a: 'aaaa', b: 'bbbb'})
==

var getObj = function getObj() {
  return { a: 'aaaa', b: 'bbbb' };
};
const full = ({firstName, lastName}) => firstName + lastName;
==
var full = function full(_ref) {
  var firstName = _ref.firstName,
      lastName = _ref.lastName;
  return firstName + lastName;
};
const isEven = n => n%2 == 0;
const square = n => n*n;
==
var isEven = function isEven(n) {
  return n % 2 == 0;
};
var square = function square(n) {
  return n * n;
};

//简化回调函数

[1,2,3].map(x=>x*x)
==
[1, 2, 3].map(function (x) {
  return x * x;
});
var result = [11,2,8,23,1].sort((a,b)=>a-b)
==
var result = [11, 2, 8, 23, 1].sort(function (a, b) {
  return a - b;
});

//this 指向定义时所在的对象

function foo(){
  setTimeout(()=>{
    console.log(this.id)
  },100)
}

foo.call({id:'1001'})

//this指向foo的this 等同于下面的函数
function foo() {
  var _this = this;

  setTimeout(function () {
    console.log(_this.id);
  });
}

foo.call({ id: '1001' });
var handler = {
  id: '123456',
  init: function(){
    document.addEventListener('click', event => this.doSomething(event.type), false)
  },
  doSomething(type){
    console.log('Handing ' + type + ' for ' + this.id);
  }
}
原文地址:https://www.cnblogs.com/xudy/p/6804060.html