大家好,又见面了,我是你们的朋友全栈君。
首先定义一个父类:
//构造函数
function Animal(name) {
this.name = name || 'Animal';
this.sleep = function() {
console.log(this.name + '正在睡觉!');
};
}
//原型上面的方法:
Animal.prototype.eat = function(food) {
console.log(this.name + '正在吃:' + food);
}
//核心:将父类的实例作为子类的原型
function Dog() {
}
Dog.prototype = new Animal(); //将Animal的实例挂载到了Dog的原型链上
//或:
//Dog.prototype = Object.create(Animal.prototype)
Dog.prototype.name = 'dog';
var dog = new Dog();
console.log(dog.name); //dog
dog.eat('bone'); //dog正在吃:bone
dog.sleep(); //dog正在睡觉!
console.log(dog instanceof Animal); //true
console.log(dog instanceof Dog); //true
特点:
缺点
//核心:使用父类的构造函数增强子类实例,等于是复制父类的实例属性给子类(没用到原型)
function Cat(name) {
Animal.call(this);
this.name = name || 'Tom';
}
var cat = new Cat();
console.log(cat.name); //Tom
cat.sleep(); //Tom正在睡觉!
console.log(cat instanceof Animal); //false
console.log(cat instanceof Cat); //true
特点:
缺点:
//核心:为父类实例添加新特性,作为子类实例返回
function Cat(name) {
var instance = new Animal();
instance.name = name || 'Tom';
return instance;
}
var cat = new Cat();
console.log(cat.name); //Tom
cat.sleep(); //Tom正在睡觉!
console.log(cat instanceof Animal); //true
console.log(cat instanceof Cat); //false
特点:
缺点:
function Cat(name){
var animal = new Animal();
for(let i in animal) {
Cat.prototype[i] = animal[i];
}
Cat.prototype.name = name || 'Tom';
}
var cat = new Cat();
console.log(cat.name); //Tom
cat.sleep(); //Tom正在睡觉!
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true
特点:
缺点:
//核心:通过调用父类构造,继承父类的属性并保留传参的优点,然后通过将父类实例作为子类原型,实现函数复用
function Cat(name) {
Animal.call(this);
this.name = name || 'Tom';
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
var cat = new Cat();
console.log(cat.name); //Tom
cat.sleep(); //Tom正在睡觉
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true
特点:
缺点:
//核心:通过寄生方式,砍掉父类的实例属性,这样,在调用俩次父类的构造的时候,就不会初始化俩次实例方法/属性,避免了组合继承的缺点。
function Cat(name) {
Animal.call(this);
this.name = name || 'Tom';
}
(function() {
var Super = function() {
}; //创建一个没有实例的方法类。
Super.prototype = Animal.prototype;
Cat.prototype = new Super(); //将实例作为子类的原型。
})();
let cat = new Cat();
console.log(cat.name); //Tom
cat.sleep(); //Tom正在睡觉
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); //true
Cat.prototype.constructor = Cat; //修复构造函数
特点:
缺点:
语法糖,底层任然是原型链继承的方式 https://es6.ruanyifeng.com/#docs/class-extends
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/163409.html原文链接:https://javaforall.cn