[08] JavaScript 入門 - 模組、this


keywords:module,this

模組 ( Module )

搭配上一章最後講的閉包,在 JavaScript 最常見的用法是模組模式( module pattern )。
先來看範例:

    function Vehicle(){
      let name,color;

      function moveOn(name,color){
        vehicleName = name;
        vehicleColor = color;

        console.log('name:',vehicleName);
        console.log('color:',vehicleColor);
      }

      const publicAPI = {
        move: moveOn
      };

      return publicAPI;
    };

    const tesla = Vehicle();
    tesla.move('car','red');  // name: car color: red
  • Vehicle() 函式是一個外層範疇,持有變數 name,color ,還有 moveOn 函式,這些都是 Vehicle 模組內部的部分,外層是無法直接調用或使用的。
  • 執行 Vehicle() 會建立 Vehicle 模組的一個實體( instance )即 const tesla = Vehicle(); 會有一整個新的範疇被創造出來,因此有一份全新的內層變數( name,color )/ 函式(moveOn)出現,且會將這個實體指定給 tesla。
  • 🚩Vehicle 只是一個函式,並非可被實體化的類別 ( class )

this 識別字

  • this 常被認為與物件導向模式( object-oriented patterns )有關,但實際上是不同的機制。
  • 一個函式裡有一個 this 參考,這個 this 參考通常指向一個 object , this 指向什麼得檢視目標函式是如何被呼叫的this 並不是參考到該函式本身
    先來看範例:

      function f1() {
        console.log( this.bar )
      }
    
      var bar = 'global'
    
      const obj1 = {
        bar: 'obj1',
        f1: f1
      }
    
      const obj2 = {
        bar: 'obj2'
      }
    
      f1()  // global  
      非 strict 模式下, this 被設定為全域物件
      strict 模式下, this 會是 undefined
    
      obj1.f1() // obj1
      將 this 設為了 obj1 物件
    
      f1.call(obj2) // obj2
      將 this 設為了 obj2 物件
    
      new f1() // undefined
      將 this 設為了一個全新的空物件
    
#module #this







你可能感興趣的文章

JAVA筆記_Thread 多線程

JAVA筆記_Thread 多線程

MPLAB X IDE 黑色主題

MPLAB X IDE 黑色主題

Vite系列# 部署 Vite 專案至 GitHub Pages

Vite系列# 部署 Vite 專案至 GitHub Pages






留言討論