JavaScript如何实现继承的几种方法
程序员文章站
2022-04-10 15:39:05
...
<script>
//1.借助构造函数继承
function parent() {
this.name = "parent"
}
parent.prototype.say = 'say'
function child() {
parent.call(this);
this.type = 'child'
}
// console.log(new child)
//缺点:不会继承原型链上的属性。
//2.通过原型链来继承
function parent1() {
this.name = "parent1"
this.arr = [1, 2]
}
function child1() {
this.type = 'child1'
}
child1.prototype = new parent1();
var s1 = new child1()
var s2 = new child1()
s1.arr.push(3)
//console.log(s1)
//console.log(s2)
//缺点:修改父类的属性值,会改变所有子类中继承的值,原型链中的原型对象是共用的。
//3.组合继承
function parent2() {
this.name = "parent2"
}
function child2() {
parent2.call(this);
this.type = 'child2'
}
child2.prototype=new parent2();
//console.log(new child2)
//缺点:父级构造函数执行了的两次
//3.1组合继承的优化
function parent3() {
this.name = "parent3"
}
function child3() {
parent3.call(this);
this.type = 'child3'
}
child3.prototype=parent3.prototype;
//console.log(new child3)
//缺点:无法判断对象是由谁直接实例化的
//3.2组合继承的优化
function parent4() {
this.name = "parent4"
}
function child4() {
parent4.call(this);
this.type = 'child4'
}
child4.prototype=Object.create(parent4.prototype)//隔离构造函数
child4.prototype.constructor=child4;//重新赋值构造函数
//4.es6 class与extends来实现继承
class parent5{
constructor(name){
this.name=name
}
}
class children5 extends parent5{
constructor(name,type){
super(name)
this.type=type
}
}
console.log(new children5('1','2'))
</script>