<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// ES5 的继承语法
// 语法1: 原型继承
// 语法2: 借用构造函数继承
// 语法3: 组合继承
// 语法1: 原型继承
// 所谓的原型继承,就是通过 原型链 将父类构造函数 和 子类 构造函数 串联起来
// 所谓的原型链,本质就是通过 __proto__ 将实例化对象,构造函数 串联起来,可以调用数据
// 实例化对象,通过 __proto__ 访问 构造函数 prototype 中存储的函数方法
// 父类构造函数 <--- 实例化对象 <--- 子类构造函数
// 定义的父类构造函数
// function Father(name,age){
// this.name = name;
// this.age = age;
// }
// Father.prototype.fun1 = function(){};
// Father.prototype.fun2 = function(){};
// 通过父类构造函数生成一个实例化对象
// const objFather = new Father('张三',18);
// 定义一个子类构造函数
// function Son(){}
// 在子类的 prototype 中 添加 父类构造函数生成的实例化对象
// Son.prototype = objFather;
// console.dir(Son);
// 执行效果
// 因为添加的是 父类生成的实例化对象
// 实例化对象的属性和属性值,都是定义好的,不能修改
// 实际上,我们可以调用的是父类的 函数方法
// 语法2: 借用构造函数继承
// 主要继承 属性
// 定义父类构造函数
// function Father(name,age){
// this.name = name;
// this.age = age;
// }
// Father.prototype.fun1 = function(){};
// Father.prototype.fun2 = function(){};
// // 使用父类构造函数,生成一个对象
// const objFather = new Father('张三' , 18);
// // 定义子类构造函数
// function Son(sex){
// // 调用父类构造函数,this的指向就会出现问题
// // 要通过 call 方法,改变this指向
// // 父类构造函数的this指向,应该是父类生成的实例化对象
// // 现在需要指向子类构造函数生成的实例化对象,也就是子类的this
// // 这里的this,在子类构造函数中,就是子类的this,就是指向子类构造函数生成的实例化对象
// // Father()构造函数,this的指向,变成了,子类this的指向,李四和20的两个实参
// // 就赋值给了,子类构造函数,生成的实例化对象上了
// // 效果是,通过父类,给子类生成的实例化对象,定义属性和属性值
// // 不能继承父类的函数方法
// Father.call(this , '李四' , 20);
// // 子类自定义的方法
// this.sex = sex;
// }
// const sonObj = new Son('男');
// console.log(sonObj);
// 语法3: 组合继承
// 同时使用 原型继承和借用构造函数继承
// 原型继承 可以继承父类的方法 但是不能定义继承父类的属性
// 借用构造函数继承 可以定义继承父类的属性,但是不能继承父类的方法
// 定义父类
function Father(name,age){
this.name = name;
this.age = age;
}
Father.prototype.fun1 = function(){};
Father.prototype.fun2 = function(){};
// 使用父类构造函数,生成一个对象
const objFather = new Father('张三' , 18);
// 创建子类
function Son(sex){
// 通过借用构造函数,继承父类的属性
Father.call(this,'李四' , 20);
// 定义子类,自定义属性
this.sex = sex;
}
// 通过原型继承,继承父类的方法
Son.prototype = objFather;
// 定义子类,自定义函数方法
Son.prototype.f = function(){}
const objSon = new Son('男');
console.log(objSon);
</script>
</body>
</html>