<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
// 原型链继承,子类实例化无法传参,原型中包含的引用类型属性被所有实例共享
// function Animal() {
// this.colors = ["black", "white"];
// }
// Animal.prototype.getColor = function(){
// return this.colors
// }
// function Dog(){}
// Dog.prototype = new Animal()
// const d1 = new Dog()
// d1.colors.push('red')
// const d2 = new Dog()
// console.log(d1,d2,d1===d2);
// 借用构造函数传参,方法定义在构造函数中,每次创建子类都会创建一遍方法
// function Animal(name) {
// this.name = name;
// this.getName = function () {
// return this.name;
// };
// }
// function Dog(name) {
// Animal.call(this, name);
// }
// Dog.prototype = new Animal();
// const d1 = new Dog('tom')
// const d2 = new Dog('huahua')
// console.log(d1,d2);
// 组合继承 调用两次父类构造函数 new Animal() Animal.call()
function Animal(name) {
console.log(123456, name);
this.name = name;
}
Animal.prototype.getName = function () {
return this.name;
};
function Dog(name, age) {
Animal.call(this, name);
this.age = age;
}
Dog.prototype = new Animal();
// Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
const d1 = new Dog("tom", 12);
const d2 = new Dog("huahua", 18);
console.log(d1, d2);
</script>
</body>
</html>