1. 程式人生 > 其它 >使用export、export default匯出類Class,import匯入呼叫類的方法

使用export、export default匯出類Class,import匯入呼叫類的方法

1.首先建立一個父類Father.js,使用export default預設匯出。

'use strict';
 class Father {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    work() {
        console.log('fater in the hard work');
    }
}
export default Father;

2.在html的script中的使用,script預設寫js程式碼,或者使用src引入js檔案,預設不能使用module形式,但是script標籤上加上type=module屬性,就可以寫匯入模組。

<script type="module">
     import  Father  from './father.js';
     let father = new Father('父親', 28);
     father.work(); 
</script>

3.瀏覽器開啟html頁面,F12檢視控制檯輸出:

4.使用export,匯出一個Mother類。

'use strict';
export class Mother {
    constructor(name,age){
       this.name = name;
       this.age = age; 
    }
    
// see 是原型物件上的屬性 see(){ console.log(`mother name is ${this.name}、age ${this.age},mother Looking at the distance`); } }

在script中,使用export匯出的模組,需要使用大括號{}

import { Mother } from './mother.js';
let mother = new Mother('母親', 27);
mother.see();

但是使用exportdefault預設匯出模組,就不需要,具體兩者之間的區別,可以百度查詢。