js继承实现方法详解
网络编程 2021-07-04 19:19www.168986.cn编程入门
这篇文章主要介绍了js继承实现方法,结合实例形式分析了javascript继承的实现方法与相关注意事项,需要的朋友可以参考下
本文实例讲述了js继承实现方法。分享给大家供大家参考,具体如下
var animal=function(name){ //构造函数 this.name=name; this.sayhello=function(){ alert("hi我是"+this.name); }; } animal.prototype.shout=function(){ //prototype主要作用:给类增加一个新的属性或函数 alert(this.name+"正在叫!"); }; animal.prototype.game=function(){ alert(this.name+"正在玩耍!"); }; var dog=new animal("小黑"); //实例化 dog.sayhello(); dog.shout(); dog.game();
一、原型继承
var animal=function(name){ this.name=name; this.sayhello=function(){ alert("hi我是"+this.name); }; } animal.prototype.shout=function(){ alert(this.name+"正在叫!"); }; animal.prototype.game=function(){ alert(this.name+"正在玩耍!"); }; var Dog=function(name){ this.name=name; this.shout=function(){ //重写父类的函数 alert(this.name+"汪汪叫!"); } } Dog.prototype=Cat.prototype=new animal(); var dog=new Dog("小黑"); dog.sayhello(); dog.shout(); dog.game(); var cat=new Cat("小白"); cat.sayhello(); cat.shout(); cat.game();
animal是父类(或超类),要继承于谁,谁就是父类(超类)
改进专门写个函数,用来实现继承
var animal=function(name){ this.name=name; this.sayhello=function(){ alert("hi我是"+this.name); }; } Function.prototype.extends=function(superclass){ //extends是保留关键字,不能拿出来单独使用,如var extends=function(){},而这里可以使用是因为他做为函数的属性添加上去 this.prototype=new superclass(); }; animal.prototype.shout=function(){ alert(this.name+"正在叫!"); }; animal.prototype.game=function(){ alert(this.name+"正在玩耍!"); }; var Dog=function(name){ this.name=name; this.shout=function(){ alert(this.name+"汪汪叫!"); } } Dog.extends(animal); var dog=new Dog("小黑"); dog.sayhello(); dog.shout(); dog.game(); var dog=new Dog("小白"); dog.sayhello(); dog.shout(); dog.game();
二、call,apply继承(不完全继承)
var animal=function(name){ this.name=name; this.sayhello=function(){ alert("hi我是"+this.name); }; } animal.prototype.shout=function(){ alert(this.name+"正在叫!"); }; animal.prototype.game=function(){ alert(this.name+"正在玩耍!"); }; var Dog=function(name){ animal.call(this,name); } var dog=new Dog("小黑"); dog.sayhello(); dog.shout(); dog.game();
输出hi我是小黑
TypeError: dog.shout is not a function
通过call(apply)的方式,只能改变其this指向,通过prototype添加进去的方法,他是无法直接继承的
call,apply这种方式的继承适用于没有prototype的类或者不需要继承prototype所添加属性或函数的类,因为call和apply函数只是实现了方法的替换,而没有对对象的属性和函数进行复制操作
原型继承,则可以继承所有的属性和函数
继承的属性,只有删除原有属性,才会输出继承的属性
更多关于JavaScript相关内容可查看本站专题《》、《》、《》、《》、《》、《》、《》及《》
希望本文所述对大家JavaScript程序设计有所帮助。
编程语言
- 宿迁百度关键词排名指南:实现精准营销的关键
- 四川SEO优化怎么做网络推广
- 立昂技术备案老域名收购:如何为您的业务赋能
- 安徽百度关键词seo贵不贵,一般需要多少钱
- 吉林百度快照排名怎么做电话营销
- 多伦新手做SEO怎么做
- 甘肃优化关键词排名推广怎么做论坛营销
- 沙雅SEO网站推广:提升您的在线可见性
- 四川SEO优化如何提升销售额和销售量
- 聂荣网站排名优化:提升网站可见性的全方位指
- 涞水SEO:提升地方企业在线可见性的策略
- 辽宁百度seo排名怎样做网站排名
- 临湘哪有关键词排名优化:提升网站可见度的关
- 黑龙江百度网站优化有没有优惠
- 凉城优化关键词排名推广:提升您的网络可见性
- 萝北整站优化:提升您网站流量和排名的全面指