一、Class
ES6中的Class用法類似Java的Class用法,但class的本質是js一個function
//定義類 class Person { //定義構造方法 constructor(name, age){ console.log("父類構造方法") this.name = name; this.age = age; } getInfo(){ return `姓名:${this.name} , 年齡: ${this.age}`; } } let person = new Person("Jack", 10); console.log(person); console.log(person.getInfo()); //通過extends 實現繼承 class BlackPerson extends Person{ constructor(name, age, height){ super(name, age); console.log("子類構造方法"); this.height = height; } //重寫父類方法 getInfo(){ return `姓名:${this.name} , 年齡: ${this.age} , 身高: ${this.height}`; } } let xiaohei = new BlackPerson("xiaohei", 24, 160); console.log(xiaohei); console.log(xiaohei.getInfo());
二、模塊化export
在創建JavaScript模塊時,export
語句用於從模塊中導出函數、對象或原始值,以便其他程序可以通過 import
語句使用它們。
export.js
let name = 'Jack'; let age = 11; let func = function () { return `姓名: ${name} ,年齡:${age}`; }; let myclass = class myClass{ static a = "呵呵"; } //export {name, age, func, myclass}; export default { name: name, age: age, getInfo(){ return `姓名:${this.name} , 年齡: ${this.age}`; } }
es6模塊.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 1 <script type="module"> //import {name, age, func, myclass}; import student from "./js/export.js"; console.log(student); console.log(student.getInfo()); </script> </body> </html>
結果:
Reference: