js继承实现方法详解
#代码知识 发布时间: 2026-01-11
本文实例讲述了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面向对象入门教程》、《JavaScript中json操作技巧总结》、《JavaScript切换特效与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。
代码知识SEO上一篇 : 详解jQuery简单的表格应用
下一篇 : 详解MVC如何使用开源分页插件(shenniu.pager.js)
-
SEO外包最佳选择国内专业的白帽SEO机构,熟知搜索算法,各行业企业站优化策略!
SEO公司
-
可定制SEO优化套餐基于整站优化与品牌搜索展现,定制个性化营销推广方案!
SEO套餐
-
SEO入门教程多年积累SEO实战案例,从新手到专家,从入门到精通,海量的SEO学习资料!
SEO教程
-
SEO项目资源高质量SEO项目资源,稀缺性外链,优质文案代写,老域名提权,云主机相关配置折扣!
SEO资源
-
SEO快速建站快速搭建符合搜索引擎友好的企业网站,协助备案,域名选择,服务器配置等相关服务!
SEO建站
-
快速搜索引擎优化建议没有任何SEO机构,可以承诺搜索引擎排名的具体位置,如果有,那么请您多注意!专业的SEO机构,一般情况下只能确保目标关键词进入到首页或者前几页,如果您有相关问题,欢迎咨询!