javascript继承方法有哪些
时间:2021-04-09
来源:互联网
标签:
今天PHP爱好者给大家带来javascript继承方法有:1、使用call()方法,可以编写能够在不同对象上使用的方法;2、apply()方法,语法“apply(用作 this 的对象,要传递给函数的参数的数组)”。希望对大家有所帮助。
本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
1、call() 方法
call() 方法是与经典的对象冒充方法最相似的方法。它的第一个参数用作 this 的对象。其他参数都直接传递给函数自身
function Huster(name,idNum,college)
{ this.name = name;
this.idNum = idNum;
this.college = college;
this.course = new Array();
this.addCourse = function(course)//这个方法不能用prototype来定义,如果用的话,子类无法继承该方法
{ //用原型prototype定义的方法可以用原型链来继承,call()方法和apply()方法都无法继承 this.course.push(course);
console.log(this.course);
};
}
function Autoer(name,idNum)
{
this.college = ‘自动化‘;
Huster.call(this,name,idNum,this.college);//Autoer使用call()方法来继承 Huster
if (typeof Autoer._initialized == "undefined")
{
Autoer.prototype.sayHobby = function() //自己的方法可以用原型链prototype定义
{
alert(this.college+‘人喜欢撸代码!‘);
};
Autoer._initialized = true;
}
}
var autoer1 = new Autoer(‘偶人儿‘,‘U123456789‘); //声明一个实例autoer1
console.log(autoer1.name,autoer1.idNum,autoer1.college,autoer1.course);
autoer1.addCourse(‘logistics‘);//调用Huster的方法
autoer1.sayHobby(); //调用自身的方法
2、apply() 方法
apply() 方法与call()方法几乎一样,唯一的区别就是apply()方法只有两个参数,第一个用作 this 的对象,第二个是要传递给函数的参数的数组。也就是说apply()方法把call()方法的若干个参数放到一个数组里,传递给父类
function Huster(name,idNum,college){
this.name = name;
this.idNum = idNum;
this.college = college;
this.course = new Array();
this.addCourse = function(course)//这个方法不能用prototype来定义,如果用的话,子类无法继承该方法
{ //用原型prototype定义的方法可以用原型链来继承,call()方法和apply()方法都无法继承
this.course.push(course);
console.log(this.course);
};
}
function Autoer(name,idNum)
{
this.college = ‘自动化‘;
Huster.apply(this,new Array(name,idNum,this.college));//Autoer使用apply()方法来继承 Huster
if (typeof Autoer._initialized == "undefined")
{
Autoer.prototype.sayHobby = function() //自己的方法可以用原型链prototype定义
{
alert(this.college+‘人喜欢撸代码!‘);
};
Autoer._initialized = true;
}
}
var autoer1 = new Autoer(‘偶人儿‘,‘U123456789‘); //声明一个实例autoer1
console.log(autoer1.name,autoer1.idNum,autoer1.college,autoer1.course);
autoer1.addCourse(‘logistics‘);//调用Huster的方法
autoer1.sayHobby(); //调用自身的方法
以上就是javascript继承方法有哪些的详细内容,更多请关注php爱好者其它相关文章!
-
访问网站出现nginx怎么解决?welcome to nginx!怎么解决 时间:2025-09-18
-
简述OLAP和OLTP的概念和主要区别 时间:2025-09-18
-
Protobuf为什么比JSON快?两者之间的性能对比 时间:2025-09-18
-
Wifi协议802.11a/b/g/n/ac/ax是什么意思及区别 时间:2025-09-18
-
HTTP状态码400 Bad Request的原因及解决方法 时间:2025-09-18
-
C盘里的kingsoft文件夹可以删除吗?kingsoft文件夹有什么用? 时间:2025-09-18
今日更新
-
蛋仔派对蛋仔步行街惊喜升级-将上线多个开店实用功能
阅读:18
-
鼠标滚轮乱跳问题怎么解决 3种修复方法快速搞定
阅读:18
-
鼠标滚轮失灵怎么办?快速修复方法和原因全解析
阅读:18
-
崩坏星穹铁道多少抽保底-保底机制详细
阅读:18
-
使命召唤手游X白夜极光联动武器9月19日将返场
阅读:18
-
鼠标跟随文字特效教程:零基础实现网页动态交互效果 (46个字,包含关键词"鼠标跟随文字",突出"教程"和"零基础"吸引目标用户,使用"动态交互效果"强化技术价值,符合百度SEO标题规范)
阅读:18
-
鼠标滚轮失灵怎么办?快速修复方法及原因解析
阅读:18
-
航海王壮志雄心高招多少抽保底-高招保底机制
阅读:18
-
燕云十六声全新外观套装啸月公布-9月19日将正式登场
阅读:18
-
三国谋定天下马超是核心吗-马超强度详细解析
阅读:18