1. 程式人生 > >js學習筆記04-ES6函數(箭頭函數與this),class

js學習筆記04-ES6函數(箭頭函數與this),class

箭頭函數 函數參數默認值 ES6 類的創建

箭頭函數

讓簡短單行函數更容易編寫和閱讀的
普通函數可以是函數聲明或函數表達式,但是箭頭函數始終是表達式
普通函數(把名字轉換為大寫)

const upperNames = [‘Fish‘, ‘RedHands‘, ‘Sugarbeans‘].map(function(name) { 
  return name.toUpperCase();
});

將函數轉換為箭頭函數,函數主體只有一個表達式,簡寫主體語法
1)刪掉關鍵字 function
2)刪掉圓括號
3)刪掉左右花括號
4)刪掉關鍵字 return
5)刪掉分號
6)在參數列表和函數主體之間添加一個箭頭(=>)

const upperNames = [‘Fish‘, ‘RedHands‘, ‘Sugarbeans‘].map( name => name.toUpperCase() );

箭頭函數的主體內需要多行代碼,常規主體語法
1)它將函數主體放在花括號內
2)有返回內容也需要使用 return。

箭頭函數存儲在變量中

多個或者0個參數就需要將參數列表放在()
有時候‘‘_"表示一個參數,但是不使用它

const greet = name=>`Hello ${name}`;
greet("fish");
const students = (name,age) =>`Hello My name is ${name}, I‘m ${age}`;
students("fish",19);
const firstDemo = _=>`Hello world!`;  //參數為"_"

箭頭函數中的this

箭頭函數內的,this 的值與函數外面的 this 的值一樣

function IceCream() {
  this.scoops = 0;
}
IceCream.prototype.addScoop = function() {
  const cone = this; // 設置 `this` 給 `cone`變量 ,如果使用箭頭函數就不需要
  setTimeout(function() {
    cone.scoops++; // 引用`cone`變量
    console.log(‘scoop added!‘);
  }, 500);
};
const dessert = new IceCream();
dessert.addScoop(); //500毫秒之後,dessert.scoops = 1

上面的閉包代碼用箭頭函數就可以不需要變量cone

function IceCream() {
  this.scoops = 0;
}
// 為 IceCream 添加 addScoop 方法
IceCream.prototype.addScoop = function() {
  setTimeout(()  => {
   this.scoops++; //直接使用函數外的對象
    console.log(‘scoop added!‘);
  }, 500);
};

函數參數默認值

function getName(name){
    name = (typeof name !== ‘undefined‘) ? name : ‘fish‘; 
    return name;
}
function getName(name = "fish") {    // 添加等號 ( = ) 以及默認值
    return name;
}

默認值和解構數組

// = []  防止調用無參函數報錯 Cannot read property ‘Symbol(Symbol.iterator)‘ of undefined
 function createGrid([width = 5, height = 5] = []) {  //=[], createGrid()可以直接使用
  return `Generating a grid of ${width} by ${height}`;
}

默認值和解構對象

函數可以讓對象成為一個默認參數,並使用對象解構
與數組默認值相比,因為數組是基於位置的,對象默認值具備的一個優勢是跳過參數進行處理
而數組是基於位置的,需要傳入 undefined 以跳過參數

//={} 同數組一樣
function createSundae({scoops = 1, toppings = [‘Hot Fudge‘]} = {}) {
  const scoopText = scoops === 1 ? ‘scoop‘ : ‘scoops‘;
  return `Your sundae has ${scoops} ${scoopText} with ${toppings.join(‘ and ‘)} toppings.`;
}

ES6 class創建類

ES5 構造函數創建“類”

function Plane(numEngines) {  //Plane 函數是一個構造函數
  this.numEngines = numEngines;
  this.enginesActive = false;
}
// 由所有實例 "繼承" 的方法
Plane.prototype.startEngines = function () {
  console.log(‘starting engines...‘);
  this.enginesActive = true;
};
const richardsPlane = new Plane(1); //使用new創建新的 Plane 對象
richardsPlane.startEngines();
const jamesPlane = new Plane(4);
jamesPlane.startEngines();

新的 class 語法編寫後的代碼

class Plane { //
  constructor(numEngines) {
    this.numEngines = numEngines;
    this.enginesActive = false;
  }
startEngines() {
    console.log(‘starting engines…‘);
    this.enginesActive = true;
  }
}
typeof Plane; // function        新語法定義的類也只是一種函數

靜態方法static

靜態方法不會被實例繼承,而是直接通過類來調用
三種調用方法,調用與實例無關
1)父類直接調用
2)子類繼承父類後調用
3)子類通過super對象調用

class Foo {
  static classMethod() {
    return ‘hello‘;
  }
}
Foo.classMethod();  //hello 父類直接調用
class Bar extends Foo {
}
Bar.classMethod();  //hello 子類繼承父類調用
class Cla extends Foo {
    return super.classMethod(); //hello super調用
}

super和extends

子類繼承父類使用關鍵字 extends
在構造方法中,super 被用作函數,如果子類的構造方法中有this和super,super必須放在this的前面使用。在子類的方法中,super 被用作對象,調用父類的方法

 class Tree {  // ES6 創建類,子類
  constructor(size = ‘10‘, leaves = {spring: ‘green‘, summer: ‘green‘, fall: ‘orange‘, winter: null}) {
    this.size = size;
    this.leaves = leaves;
    this.leafColor = null;
  }
changeSeason(season) {
    this.leafColor = this.leaves[season];
    if (season === ‘spring‘) {
      this.size += 1;
    }
  }
}

class Maple extends Tree { //繼承父類
  constructor(syrupQty = 15, size, leaves) {
    super(size, leaves); //構造方法中的super
    this.syrupQty = syrupQty;
  }
changeSeason(season) {
    super.changeSeason(season); //子類方法中的super
    if (season === ‘spring‘) {
      this.syrupQty += 1;
    }
  }
 gatherSyrup() {
    this.syrupQty -= 3;
  }
}
function Tree(size, leaves) {  //ES5創建類,子類
  this.size = size || 10;
  this.leaves = leaves || {spring: ‘green‘, summer: ‘green‘, fall: ‘orange‘, winter: null};
  this.leafColor;
}
Tree.prototype.changeSeason = function(season) {
  this.leafColor = this.leaves[season];
  if (season === ‘spring‘) {
    this.size += 1;
  }
}

function Maple (syrupQty, size, leaves) {  //子類
  Tree.call(this, size, leaves);  //使用父類的屬性
  this.syrupQty = syrupQty || 15;
}
Maple.prototype = Object.create(Tree.prototype); //函數原型設置為基類原型
Maple.prototype.constructor = Maple;//重新建立constructor和構造函數的連接
Maple.prototype.changeSeason = function(season) {
  Tree.prototype.changeSeason.call(this, season);  //重寫父類的方法
  if (season === ‘spring‘) {
    this.syrupQty += 1;
  }
}
Maple.prototype.gatherSyrup = function() {
  this.syrupQty -= 3;
}

Tree.call(this, size, leaves);
Maple.prototype = Object.create(Tree.prototype);
Maple.prototype.constructor = Maple;

js學習筆記04-ES6函數(箭頭函數與this),class