ES6入門教程——11、ES6函數

一、對參數的擴展

1、默認值

function fn(name,age=17){
 console.log(name+","+age);
}
fn("darlin",19);  // darlin,19
fn("darlin","");  // darlin,
fn("darlin");     // darlin,17

2、不定參數

function f(...values){
    console.log(values.length);
}
f(1,2);      //2
f(1,2,3,4);  //4

二、箭頭函數

語法

參數 => 函數體

基本用法:

var f = v => v; 

//等價於 

var f = function(a){ 
      return a; 
} 
f(1); //1

this的含義:指的是外層函數。

var func = () => {
  // 箭頭函數裏面沒有 this 對象,
  // 此時的 this 是外層的 this 對象,即 Window 
  console.log(this)
}
func(55)  // Window 


function fn(){
  setTimeout(()=>{
    // 定義時,this 綁定的是 fn 中的 this 對象
    console.log(this.a);
  },0)
}
var a = 20;
// fn 的 this 對象爲 {a: 19}
fn.call({a: 19});  // 19

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章