<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body></body>
</html>
<script>
// 继承
// 子类默认里面没有自己的this
// 必须要调用super()才能够拿到this
// class Person {
// constructor(name, age) {
// this.name = name;
// this.age = age;
// }
// sayName() {
// console.log(this);
// }
// }
// // 继承 ES6中extends关键字实现相当于是ES5中直接替换原型对象
// class Teacher extends Person {
// // 继承Person类 Person作为父类 Teacher作为子类
// constructor(name, age, job) {
// super(name, age);
// // 调用父类构造器完成子类this对象塑造
// // let this = new Person(name, age);
// // this.__proto__ = Teacher.prototype
// // this.__proto__.__proto__ = Person.prototype
// this.job = job;
// }
// teach() {
// console.log(this.job); // 英语
// }
// static hobbits = "敲代码"; // 静态属性
// static show() {
// // 静态方法
// console.log(this.hobbits);
// }
// }
// let t1 = new Teacher("Jack", 19, "英语");
// console.log(t1);
// t1.sayName();
// t1.teach();
// 子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子
// 类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属
// 性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。
// 如果不调用super方法,子类就得不到this对象。
// ES5 的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this
// 上面(Parent.apply(this) )。ES6 的继承机制完全不同,实质是先将父类实例对象
// 的属性和方法,加到this上面(所以必须先调用super方法),然后再用子类的构造函数
// 修改this。
// 在子类的构造函数中,只有调用super之后,才可以使用this关键字,否则会报错。这是因为
// 子类实例的构建,基于父类实例,只有super方法才能调用父类实例。
// 专题训练
class China {
constructor({ people }) {
// new China()时默认执行 this = {__proto__: China.prototype} | Object.create(China.prototype)
this.people = people;
// 默认最后 return this
}
speak(language) {
console.log(language);
}
}
class Person extends China {
constructor({ name, age, people }) {
super({ people });
// 相当于执行了以下三部
// let this = new China({people}); // 得到父类China内部返回的this
// this.__proto__ = Person.prototype
// this.__proto__.__proto__ = China.prototype
this.name = name;
this.age = age;
// 默认最后 return this
}
sayHI(db) {
console.log(db + this.name);
}
}
// let p = new Person({ name: "jack", age: 19, people: "江西人" });
// console.log(p);
// p.sayHI("我叫");
class Teacher extends Person {
constructor({ name, age, job, people }) {
super({ name, age, people });
// 相当于执行了以下几步
// let this = new Person({ name, age, people }) // 这个this是China内部返回到Person再返回到Teacher中 所以属于China
// this.__proto__ = Teacher.prototype
// this.__proto__.__proto__ = Person.prototype
// this.__proto__.__proto__.__proto__ = China.prototype
// this.__proto__.__proto__.__proto__.__proto__ = Object.prototype
this.job = job;
// 默认最后 return this
}
myReport(content) {
console.log(content);
}
}
let t = new Teacher({
name: "沙雕",
age: 26,
job: "程序员",
people: "黄种人"
});
console.log(t);
t.speak("中文");
t.myReport("在座各位都是辣鸡");
t.sayHI("他的名字叫");
</script>
网友评论