您现在的位置是:课程教程文章

JavaScript有哪些继承的方法

2023-12-14 20:36课程教程文章 人已围观

1、寄生式继承,基于某个对象创建一个对象,然后增强对象,返回对象。

functioncreate(original){
//通过调用函数创建一个新对象
varclone=object(original);
//以某种方式增强对象
clone.sayHi=function(){
console.log('hi')
}
returnclone;
}
varperson={
name:'chen'
}
varperson1=create(person);
person1.sayHi();

2、原型链继承,将父类的实例作为子类的继承。

functionParent(){
this.name='parent'
}
Parent.prototype.sayName=function(){
returnthis.name
}
functionChild(){
}
//继承了Parent
Child.prototype=newParent();
varchild1=newChild();
child1.say();

3、组合继承,使用原型链继承共享的属性和方法。

通过借用构造函数继承实例属性。

functionParent(name){
this.name=name;
this.arr=[1,2,3]
}
Parent.prototype.sayName=function(){
console.log(this.name)
}
functionChild(name,age){
//继承属性
Parent.call(this,name)
this.age=age
}
//继承方法
Child.prototype=newParent()
Child.prototype.constructor=Child;
Child.prototype.sayAge=function(){
console.log(this.age)
}
varchild1=newChild('chen',21);
child1.arr.push(4);//[1,2,3,4]
child1.sayName()//'chen'
child1.sayAge()//21

varchild2=newChild('miao',12)
child2.arr//[1,2,3]
child2.sayName()//"miao"
child2.sayAge()//12

以上就是JavaScript继承的方法,希望对大家有所帮助。更多Javascript学习指路:Javascript

推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。

课程教程:JavaScript有哪些继承的方法

上一篇:JavaScript如何减少重绘和回流

下一篇:没有了

站点信息

  • 文章统计篇文章