<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
/**
* 构造函数Person
* @constructor
*/
function Person(name, pets) {
this.name = name;
this.pets = pets;
}
Person.prototype.run = function () {
console.log('跑');
};
/**
* 构造函数Student
* @constructor
*/
function Student(num, name, pets) {
// 注意: 一定要放在最前面
Person.call(this, name, pets); // ★借助构造函数继承call/apply★
this.num = num;
}
// ★寄生式继承★
function Temp() {} // 定义一个空类,用于寄生Person原型属性方法
Temp.prototype = Person.prototype; // 使Temp原型指向Person原型
var stuPrototype = new Temp(); // 实例化一个对象 原型指向Person原型
Student.prototype = stuPrototype; // 改变子类student的原型指向
stuPrototype.constructor = Student; // 确保原型中的constructor指向Student构造函数
</script>
<script>
var stu = new Student('001', '张三', ['小花']);
var stu2 = new Student('002', '李四', ['小茂']);
console.log(stu);
console.log(stu2);
</script>
</body>
</html>
寄生式组合继承(最常用、最完美继承方式):借助构造函数继承+寄生式继承
最新推荐文章于 2024-03-03 16:34:44 发布