官方推荐用, 然而一用就报错, 主要是报在this上面.

mdn说了:

  1. 这个是匿名函数
  2. 没有自己的thisargumentssupernew.target

mdn: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions

可以各种简写:

() => 42;
_ => 42 //这个和上面等价

var timesTwo = params => params * 2
timesTwo(4);  // 8

x =>({ y: x }) //这样就直接返回了一个对象{ y: x }, 省略了return, 等同于 return { y: x }

es6提供了更简洁的写法

var person = {
  name: "Jason",
  // ES6 "method" declaration - leave off the ":" and the "function"
  shout() {
    console.log("Hi, my name is", this.name);
  }
};

这个解释非常清晰(kamituel): https://stackoverflow.com/questions/28798330/arrow-functions-and-this

window.name = "global";

var person = {
    name: "jason",

    shout: function () {
        console.log("my name is ", this.name);
    },
    shout2: () => {
        console.log("my name is ", this.name);
    },
    // Shorter syntax
    shout3() {
        console.log("my name is ", this.name);
    }
};

person.shout();  // "jason"
person.shout2(); // "global"
person.shout3(); // "jason"

mdn有解释:

objectName.methodname = functionName;

var myObj = {
  myMethod: function(params) {
    // ...do something
  }

  // OR THIS WORKS TOO

  myOtherMethod(params) {
    // ...do something else
  }
};

js的世界函数才是第一公民, this再函数内才算被包好了. 放在对象里面this就诡异了.

get set也就好理解了.

var o = {
  a: 7,
  get b() { 
    return this.a + 1;
  },
  set c(x) {
    this.a = x / 2;
  }
};

console.log(o.a); // 7
console.log(o.b); // 8
o.c = 50;
console.log(o.a); // 25

完整的语法:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions

var obj = {
  property( parameters ) {},
  *generator( parameters ) {},
  async property( parameters ) {},
  async* generator( parameters ) {},

  // with computed keys:
  [property]( parameters ) {},
  *[generator]( parameters ) {},
  async [property]( parameters ) {},

  // compare getter/setter syntax:
  get property() {},
  set property(value) {}
};