跳到主內容

【ES6】箭頭函式

改寫原 functoin

// 傳統寫法
function fn(a, b) {
  return a * b;
}
// 箭頭函式
const fn = (a, b) => {
  return a * b;
}
// 省略 return
const fn = (a, b) => {
  a * b;
}
/////////////////////////////
function fn(name) {
  return "Hello"+name;
}
// 單行省略 return , {}
const fn = (name) => "Hello "+name;

this 指向不會指向全域,而是指向自己

var name = '全域'
const person = {
  name: '小明',
  callName: function () { 
    console.log('1', this.name); // 1 小明
    setTimeout(function () {
      console.log('2', this.name); // 2 全域
      console.log('3', this); // 3 window
    }, 10);
  },
}