JS中实现继承的7中方式

编程入门 行业动态 更新时间:2024-10-09 14:22:49

JS中实现继承的7中<a href=https://www.elefans.com/category/jswz/34/1771414.html style=方式"/>

JS中实现继承的7中方式

1.原型链继承:将父类的实例作为子类的原型

// 定义一个父类型
function Animal(name) {this.name = name;this.say = function(){ console.info('I am ' + this.name); }
}
// 原型对象方法
Animal.prototype.eat = function(food) {console.info(this.name + '正在吃' + food);
}
// 定义子类
function Cat() {}
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';
var cat = new Cat();

继承链:

缺点:创建子类实例时,无法向父类构造函数传递参数,。

2.构造函数继承:

// 定义一个父类型
function Animal(name) {this.name = name;this.say = function(){ console.info('I am' + this.name); }
}
// 原型对象方法
Animal.prototype.eat = function(food) {console.info(this.name + '正在吃' + food);
}
// 定义子类
function Cat(name, age) {Animal.call(this, name);this.age = age;
}
var cat = new Cat();

3.实例继承:

// 定义一个父类型
function Animal(name) {this.name = name;this.say = function(){ console.info('I am' + this.name); }
}
// 原型对象方法
Animal.prototype.eat = function(food) {console.info(this.name + '正在吃' + food);
}
// 定义子类
function Cat(name,age) {// 先创建子类实例var o = new Animal(name);o.age = age;return o;
}
var cat = new Cat();

4.拷贝继承: 无法获取父类不可for in遍历的方法

// 定义一个父类型
function Animal (name) {this.name = name;this.say = function(){ console.log(I’m this.name); } }
// 原型对象方法
Animal.prototype.eat = function(food) {console.log(this.name + '吃:' + food);
};
function Cat(name,age){var animal = new Animal(name);for(var p in animal){Cat.prototype[p] = animal[p]; }this.age = age 
}
var cat = new Cat();

5. 组合继承:

// 定义一个父类型
function Animal (name) {this.name = name;this.say = function(){ console.log(I’m this.name); } }
// 原型对象方法
Animal.prototype.eat = function(food) {console.log(this.name + '吃:' + food);
};
function Cat(name,age){Animal.call(this,name);this.age = age
}
Cat.prototype = new Animal(); 
Cat.prototype.constructor = Cat; 
var cat = new Cat();

6. 寄生组合继承:

// 定义一个父类型
function Animal (name) {this.name = name;this.say = function(){ console.log(I’m this.name); } }
// 原型对象方法
Animal.prototype.eat = function(food) {console.log(this.name + '吃:' + food);
};
function Cat(name,age){ Animal.call(this,name); this.age = age
} 
(function(){ // 创建一个没有实例方法的类var Super = function(){};Super.prototype = Animal.prototype; //将实例作为子类的原型 Cat.prototype = new Super();})();var cat = new Cat();

7. ES6 class extends继承:

Class 父类型{ constructor(){
}
... }

更多推荐

JS中实现继承的7中方式

本文发布于:2024-03-11 22:42:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1730094.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方式   JS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!