原本的继承:
- 原本的继承步骤:
/*
如何区分一个函数是不是构造函数?
解:根据他的使用方法来判断
使用构造函数和ES6的类设计并测试以下需要
需求1:
现在2个人, 都有姓名与年龄(值自己指定), 都能自我介绍自己的姓名和年龄, 能得到当前的总人数
需求2:
现在又有了一个学生, 它有身价的属性, 能介绍它的所有信息
又有一个老师, 它有教授课程的属性, 能介绍它的所有信息
*/
//需求一: 定义一个Person为父类,实例化两个子类p1和p2
function Person(name,age){
this.name=name;
this.age=age;
//每一次调用这个函数,总人数就应该+1
Person.prototype.count++;
}
//假设一开始总人数 = 0
Person.prototype.count = 0;
let p1 = new Person('xiaoming',23);
let p2 = new Person('xiaowang',18);
Person.prototype.sayHello = function(){
console.log(`我叫${this.name},我今年${this.age}岁`)
}
p1.sayHello();
p2.sayHello();
//需求二:子类Student要继承父类Person,并且拥有自己的属性price
function Student(name,age,price){
// 经过这一步,父类实例对象所具有的所有属性,子类实例都有
Person.call(this,name,age);
this.price=price;
}
//继承父类
Student.prototype = new Person();
Student.prototype.constructor = Student;
Student.prototype.sayHello=function(){
console.log(`我叫${this.name},我今年${this.age}岁,我有${this.price}元钱`)
}
//实例化对象s1
var s1 = new Student('钱小明',19,100000000);
// 查找顺序:s1自身没有->s1.__proto__(new Person())也没有
// ->s1.__proto__.__proto__(Person.prototype)
s1.sayHello();
console.log(s1)
- 步骤解析:
ES6的继承: extends
- 原本的继承太麻烦了, 所以es6新出了一个语法糖 – extends
- 类语法:
//class 是一个定义类的关键字(是书写面向对象的语法糖,一种新语法 )
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
do() {
console.log("study");
}
}
class Child extends Person {
constructor(name, age, gender) {
//ES6中继承的子类中,如果使用构造函数constructor()那么就必须使用super()方法初始化,这样下面才可以调用this关键字。
//super()只能用在子类的构造函数之中,用在其他地方就会报错
// 这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。如果不调用super方法,子类就得不到this对象。
super(name, age);
this.gender = gender;
}
}