iT邦幫忙

0

JS ES6 箭頭函式 DAY73

箭頭函式

傳統函式

const callName = function(someone){
    return '我是' +  someone;
}
console.log(callName('皮傑先生'));

箭頭函式

// 箭頭函式
// 若是程式碼內容為表達式時,不需要大括號{}
// 若只有一個參數 可省略括號
const callName = someone => '我是' + someone;
console.log(callName('皮傑先生'));

與傳統函式不同之處

  • 沒有arguments參數

傳統函式

var nums = function(){
    console.log(arguments);
}
nums(1,2,3,4,50,100);

箭頭函式

// arguments is no defined
var nums = () =>{
    console.log(arguments);
}
nums(1,2,3,4,50,100);

解決方式

其餘參數
原型是陣列(與 arguments 不同)

var nums = (...arg) =>{
    console.log(arg);
}
nums(1,2,3,4,50,100);
  • this 綁定的差異

箭頭函式沒有自己的 this

傳統函式

var myName = '全域';
var person = {
    myName:'皮傑先生',
    callName: function(){
        console.log('1',this.myName); // 1 皮傑先生
        setTimeout(function(){
            console.log('2',this.myName); // 2 全域
            console.log('3',this); // window
        })
    }
}
person.callName();

箭頭函式

var myName = '全域';
var person = {
    myName:'皮傑先生',
    callName: function(){
        console.log('1',this.myName); // 1 皮傑先生
        setTimeout(()=>{ 
            // 這裡會用外層作用域的 this
            console.log('2',this.myName); // 2 皮傑先生
            console.log('3',this); // person
        })
    }
}
person.callName();
var myName = '全域';
var person = {
    myName:'皮傑先生',
    callName: ()=>{
        console.log('1',this.myName); // 1 全域
        setTimeout(()=>{ 
            // 這裡會用外層作用域的 this
            console.log('2',this.myName); // 2 全域
            console.log('3',this); // window
        })
    }
}
person.callName();

也無法透過 call,apply,bind 重新給予 this

const family = {
    myName:'123',
}
const fn = (a,b) =>{
    console.log(this,a,b); // window 小黑 小白
}
fn.call(family,'小黑','小白');
  • 箭頭函式無法作為建構函式使用
const fn = function(a){
    this.name = a;
}
const ArrowFn = a =>{
    this.name = a;
}
console.log(fn.prototype);
console.log(ArrowFn.prototype); // undefined
const a = new fn('a');
console.log(a);
const b = new ArrowFn('b');
console.log(b);

那今天的介紹就到這裡
若有任何問題 或 內容有誤
都可以跟我說唷/images/emoticon/emoticon41.gif


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言