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默認導出模塊,就不需要,具體兩者之間的區別,可以百度查詢。