ES6中允许使用箭头=>定义函数
let f = v => v; //等同于 let f = function (v) { return v; } function foo(a, b) { return a + b + '10' } //等同于 let foo = (a, b) => a + b + '10' // 一个参数 let add = value => value; // 两个参数 let add = (value, value2) => value + value2; let add = (value1, value2) => { return value1 + value2; } // 无参数 let fn = () => "hello world"; let doThing = () => {} // 如果箭头函数直接返回一个对象,必须在对象外面加上括号,否则会报错 let getId = id => ({ id: id, name: 'mjj' }) let obj = getId(1);使表达更简洁
const isEven = n => n % 2 == 0; const square = n => n * n;简化回调函数
//正常函数 [1,2,3].map(function (x) { return x * x; }); //箭头函数 [1,2,3].map(x => x * x);没有this绑定
let PageHandler = { id: 123, init: function () { document.addEventListener('click', function (event) { this.doSomeThings(event.type);//doSomeThings is not defined }, false); }, doSomeThings: function (type) { console.log(`事件类型:${type},当前id:${this.id}`); } } PageHandler.init(); // 解决this指向问题 let PageHandler = { id: 123, init: function () { // 使用bind来改变内部函数this指向 document.addEventListener('click', function (event) { this.doSomeThings(event.type); }.bind(this), false); }, doSomeThings: function (type) { console.log(`事件类型:${type},当前id:${this.id}`); } } PageHandler.init(); // 箭头函数没有this指向,箭头函数内部的this值只能通过查找作用域链来确定 // 如果箭头函数被一个非箭头函数所包裹,那么this的值与该函数的所属对象相等,否则则是全局的window对象 let PageHandler = { id: 123, init: function () { document.addEventListener('click', (event) => { console.log(this); this.doSomeThings(event.type); }, false); }, doSomeThings: function (type) { console.log(`事件类型:${type},当前id:${this.id}`); } } PageHandler.init();没有arguments对象
let getVal = (a,b) => { console.log(arguments); return a + b; } console.log(getVal(1,2)); //arguments is not defined不能使用new来实例化对象
let Person = ()=>{} let p1 = new Person();// Person is not a constructor注意 => 右边如果没有{},则=>默认具有return作用
//错误写法 (reason) => throw reason //正确写法 (reason) => { throw reason }