使用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();

但是使用export default默認導出模塊,就不需要,具體兩者之間的區別,可以百度查詢。



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM