<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>组合继承</title>
</head>
<body>
<script>
function Animal(category) {
this.category = category || "Animal";
}
Animal.prototype.run = function () {
console.log("Animal run");
}
function Dog(category, name) {
Animal.call(this, category); // 继承示例属性
// Animal.apply(this, [category]);
this.name = name || 'dog';
this.type = 'dog';
}
Dog.prototype = Object.assign({}, Animal.prototype); // 继承原型方法,修改不会同步继承
// Dog.prototype = Object.create(Animal.prototype); // 继承原型方法,修改会同步继承
Dog.prototype.constructor = Dog; // 复原原型指向
var dog = new Dog("dog", "小白");
Animal.prototype.walk = function () {
console.log("Animal walk");
}
console.log(dog);
for (var name in Animal.prototype) {
console.log(name);
console.log(Animal.prototype[name]);
}
</script>
</body>
</html>
网友评论