- 项目结构
- 具体代码
index.js
import Test1 from './pakeages/one/test1.js'
import Test3 from './pakeages/three/test3.js'
let btn = document.querySelector("#btn");
let test1 = new Test1();
btn.onclick = function () {
btn.innerHTML += test1.name;
let t3 = new Test3('李华', 21, '173cm')
console.log(t3);
t3.sm();
}
test1.js
import Test2 from '../two/test2.js'
export default class Test1{
static age = 18;
constructor(){
this.name = "张三"
console.log(new Test2(Test1.age));
}
}
test2.js
export default class Test2{
constructor(name){
this.name = name;
}
running(){
console.log(this.name + '在跑步ing');
}
pm(){
console.log('逻辑1');
console.log('逻辑2');
}
}
test3.js
import Test2 from '../two/test2.js'
export default class Test3 extends Test2{
constructor(name, age, height){
super(name);// -> this.name = name;
this.age = age;
this.height = height;
}
sm(){
super.pm()
console.log('逻辑3');
console.log('逻辑4');
}
}
重点示例
import
import Test1 from './pakeages/one/test1.js'
import Test3 from './pakeages/three/test3.js'
extends
export default class Test3 extends Test2
super()
在子类(派生类)的构造函数中使用this或者返回默认对象之前,必须先通过super调用父类的构造函数,否则会报错。
import Test2 from '../two/test2.js'
export default class Test3 extends Test2{
constructor(name, age, height){
super(name);// -> this.name = name; 解决代码冗余
this.age = age;
this.height = height;
}
sm(){
super.pm(); // -> 调用父类方法供子类使用
console.log('逻辑3');
console.log('逻辑4');
}
}