1.经典继承又称为构造函数继承
<script>
// 借用父构造函数继承属性
// 1.父构造函数
function Father(uname, age) {
// this指向父构造函数的对象实例
this.uname = uname;
this.age = age;
}
Father.prototype.money = function () {
console.log(100000);
};
// 2.子构造函数
function Son(uname, age, score) {
// 经典继承又称为构造函数继承
// this指向子构造函数的对象实例
Father.call(this, uname, age); //改变指向
this.score = score;
}
2.原型链继承
//Son.prototype = Father.prototype;//这样相当给地址,所以子改变,父也跟着改
//原型链继承
//子构造函数的原型指向父构造函数的原型对象
Son.prototype = new Father(); // {}的用法,所以SOn的constructor被覆盖了,指向father
// 所以需要手动指回
Son.prototype.constructor = Son;
// 子构造函数专门的方法
Son.prototype.exam = function () {
console.log("100分");
};
var son = new Son("刘德华", 18, 100);
console.log(son);
console.log(Father.prototype);
console.log(Son.prototype.constructor);
</script>
3.extends继承
<script>
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x + this.y);
}
}
// 子类继承父类加法方法,同时 拓展减法方法
class Son extends Father {
constructor(x, y) {
// 利用super 调用父类的构造函数
// super 必须在子类this之前调用
super(x, y);
(this.x = x), (this.y = y);
}
subtract() {
console.log(this.x - this.y);
}
}
var son = new Son(5, 3);
son.subtract();
son.sum();
</script>