本文摘自PHP中文网,作者醉折花枝作酒筹,侵删。
javascript继承方法有:1、使用call()方法,可以编写能够在不同对象上使用的方法;2、apply()方法,语法“apply(用作 this 的对象,要传递给函数的参数的数组)”。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
1、call() 方法
call() 方法是与经典的对象冒充方法最相似的方法。它的第一个参数用作 this 的对象。其他参数都直接传递给函数自身
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | function Huster(name,idNum,college)
{ this .name = name;
this .idNum = idNum;
this .college = college;
this .course = new Array();
this .addCourse = function (course)
{
console.log( this .course);
};
}
function Autoer(name,idNum)
{
this .college = ‘自动化‘;
Huster.call( this ,name,idNum, this .college);
if ( typeof Autoer._initialized == "undefined" )
{
Autoer.prototype.sayHobby = function ()
{
alert( this .college+‘人喜欢撸代码!‘);
};
Autoer._initialized = true ;
}
}
var autoer1 = new Autoer(‘偶人儿‘,‘U123456789‘);
console.log(autoer1.name,autoer1.idNum,autoer1.college,autoer1.course);
autoer1.addCourse(‘logistics‘);
autoer1.sayHobby();
|
2、apply() 方法
apply() 方法与call()方法几乎一样,唯一的区别就是apply()方法只有两个参数,第一个用作 this 的对象,第二个是要传递给函数的参数的数组。也就是说apply()方法把call()方法的若干个参数放到一个数组里,传递给父类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | function Huster(name,idNum,college){
this .name = name;
this .idNum = idNum;
this .college = college;
this .course = new Array();
this .addCourse = function (course)
{
this .course.push(course);
console.log( this .course);
};
}
function Autoer(name,idNum)
{
this .college = ‘自动化‘;
Huster.apply( this , new Array(name,idNum, this .college));
if ( typeof Autoer._initialized == "undefined" )
{
Autoer.prototype.sayHobby = function ()
{
alert( this .college+‘人喜欢撸代码!‘);
};
Autoer._initialized = true ;
}
}
var autoer1 = new Autoer(‘偶人儿‘,‘U123456789‘);
console.log(autoer1.name,autoer1.idNum,autoer1.college,autoer1.course);
autoer1.addCourse(‘logistics‘);
autoer1.sayHobby();
|
【推荐学习:javascript视频教程】
以上就是javascript继承方法有哪些的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
详解javascript中的回调函数
javascript bom 有什么用
详解获取javascript各种全局对象变量的方法
javascript怎么弹出对话框
html5中的script属性及js同步和异步加载实现代码详解
electron页内查找模块介绍(代码示例)
浅析typescript和react中使用ref的方法
javascript判断一个对象是否为数组的几种方法(总结)
javascript如何修改html
javascript中字符串(string)如何转json
更多相关阅读请进入《javascript》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » javascript继承方法有哪些