1.原型链继承。
<!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"];
this.color = "green";
}
Animal.prototype.getColor = function () {
return this.color;
};
function Dog() {}
// 将动物的构造函数new的对象赋值给Dog的原型
Dog.prototype = new Animal();
let dog1 = new Dog();
dog1.colors.push("brown");
let dog2 = new Dog();
console.log(dog2.colors);
console.log(dog2.getColor());
</script>
</body>
</html>
2.组合继承。
<!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(name) {
this.name = name;
this.colors = ["blue", "green"];
}
Animal.prototype.getName = function () {
return this.name;
};
//改变Dog的this指向让它指向Animal
function Dog(name, age) {
Animal.call(this, name);
this.age = age;
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;
let dog1 = new Dog("夏天", 1);
console.log(dog1.getName());
dog1.colors.push("yellow");
console.log(dog1);
let dog2 = new Dog("冬天", 2);
console.log(dog2);
</script>
</body>
</html>
3.寄生式组合继承
<!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(name) {
this.name = name;
this.colors = ["blue", "green"];
}
Animal.prototype.getName = function () {
return this.name;
};
function Dog(name, age) {
Animal.call(this, name);
this.age = age;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
let dog1 = new Dog("冬天", 1);
dog1.colors.push("red");
console.log(dog1);
console.log(dog1.getName());
let dog2 = new Dog("秋天", 2);
console.log(dog2);
console.log(dog2.getName());
</script>
</body>
</html>
4.class类继承。
<!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>
class Animal {
constructor(name) {
this.name = name;
this.colors = ["blue", "pink"];
}
getName() {
return this.name + "" + this.age;
}
}
class Dog extends Animal {
constructor(name, age) {
super(name);
this.age = age;
}
}
let dog1 = new Dog("小花", 12);
let dog2 = new Dog("小为", 11);
dog1.colors.push("hotpink");
console.log(dog1);
console.log(dog2);
</script>
</body>
</html>