第一种继承方式:
第二种继承方式: 放到原型链上
第三种继承方式:
<!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>
function Animal(name, age) {
this.name = name;
this.age = age;
this.say = function () {
console.log("say");
}
}
Animal.prototype.sport = function () {
console.log('sport')
}
var animal = new Animal('animal', 3);
// animal.say();
// animal.sport();
// 1.构造函数实现继承
function Dog() {
// console.log(this);
// Dog {}
// age: undefined
// name: undefined
// say: ƒ ()
// __proto__: Object
// constructor: ƒ Dog()
// __proto__: Object
//加了这句只是能访问父类里面的属性方法 原型上面的方法是访问不到的
Animal.call(this)
}
// let newAnimal = new Dog(); // Dog()构造函数里面回去调用
// new里面有apply 相当于 Animal.myCall(Dog())
// Dog.f = this;// this 绑定Animal 构造函数赋值给了f属性
// Dog.f(...args);// Animal 再调用的时候 Animal构造函数里面的 this指向 Dog
//1.第一种
// var dog = new Dog();
// dog.say();
// // dog.sport();//dog.sport is not a function
// // console.log(dog.__proto__);//__proto__: Object
// Dog.prototype = Animal.prototype;
// Dog.prototype.constructor = Dog;
// console.log(Dog.prototype.constructor);//ƒ Dog(name, age) {}
// console.log(Animal.prototype.constructor);//ƒ Dog(name, age) {}
// var dog = new Dog();
// dog.say();
// dog.sport();
//第二种:利用原型链
// Dog.prototype.__proto__ = Animal.prototype;
// var dog = new Dog();
// dog.say();
// dog.sport();
//第三种: 利用中间函数
// function Temp(name, age) {
// }
// Temp.prototype = Animal.prototype;
// var temp = new Temp();
// //Dog Animal Temp 的构造函数都是Dog
// // Temp.prototype.constructor = Dog;
// // temp.__proto__.constructor = Dog;
// // Animal.prototype.constructor Animal.prototype.constructor 都是Animal
// temp.constructor = Dog;
// // Dog.prototype = temp;
// // Dog.prototype = Temp.prototype;
// Dog.prototype = temp;
// // Temp.prototype.constructor = Dog;
// var dog = new Dog();
// dog.say();
// dog.sport();
// console.log(Dog.prototype.constructor);//Dog
// console.log(Animal.prototype.constructor);//Dog
// console.log(Temp.prototype.constructor);//Dog
// 4.封装js继承
function inherit(target, orgin) {
var Fn = function () { };
Fn.prototype = orgin.prototype;
var fn = new Fn();
fn.constructor = target;//?
target.prototype = fn;
}
inherit(Dog, Animal)
var dog = new Dog();
dog.say();
dog.sport();
console.log(Dog.prototype.constructor);
console.log(Animal.prototype.constructor);
console.log(Fn.prototype.constructor);//Fn is not defined
</script>
</body>
</html>