原型继承
实现思路:子类的原型指向父类的一个实例。使子函数的prototype = new 父函数(子类中创建父类的实例)
function parent() {
this.name = "lisi";
this.age = 18;
this.getName = function () {
console.log(this.age + "岁的" + this.name);
}
function getAge(){
console.log(this.age);
}
}
function child() {
this.hobby = 'eat';
}
child.prototype = new parent();//主要
var lisi = new child();
console.log(lisi.hobby); //eat
lisi.getName(); // "18岁的lisi"
console.log(lisi.age); //18
lisi.getAge()//报错
构造继承
实现思路:子函数中调用父函数是.call方法
function parent() {
this.name = "lisi";
this.age = 18;
this.getName = function () {
console.log(this.age + "岁的" + this.name);
}
}
function child() {
this.hobby = 'eat';
parent.call(this)
}
var lisi = new child();
console.log(lisi.hobby); //eat
lisi.getName(); // "18岁的lisi"
console.log(lisi.age); //18
两种方法对某个子实例修改属性都不会影响其他子实例
组合继承(组合原型链继承和借用构造函数继承)(常用)
class继承
父类
class Student {
constructor(name) {
this.name = name;
}
hello() {
alert('Hello, ' + this.name + '!');
}
}
子类
class PrimaryStudent extends Student {
constructor(name, grade) {
super(name); // 记得用super调用父类的构造方法!
this.grade = grade;
}
myGrade() {
alert('I am at grade ' + this.grade);
}
}
需要通过super(name)来调用父类的构造函数,否则父类的name属性无法正常初始化。