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爱好者其它相关文章!
-
什么是黑盒测试?有哪些常用的黑盒测试方法? 时间:2025-10-29 -
视频码率是什么意思?怎么调节好?FPS越高越好吗? 时间:2025-10-29 -
什么是子网掩码和默认网关?它们各有什么作用? 时间:2025-10-29 -
Java中System.setProperty()用法、应用场景和设置属性详解 时间:2025-10-29 -
什么是堡垒机和跳板机?两者之间有什么区别? 时间:2025-10-29 -
什么是堡垒机 堡垒机的作用功能和原理 堡垒机和防火墙的区别 时间:2025-10-29
今日更新
-
2026年加密货币投资新手必看:5大优质平台排名与指南
阅读:18
-
"皮皮虾是什么梗?揭秘网络爆火神兽的搞笑日常"
阅读:18
-
2026全球五大最稳定交易所推荐 支持法币充值交易更便捷
阅读:18
-
2026年最值得关注的加密货币:TON SOL SUI涨幅领先
阅读:18
-
键盘侠是什么梗?指网络上爱指点江山却无实际行动的网友,快来了解这一网络热词背后的真相!
阅读:18
-
2026年十大潜力公链代币:ETH、SOL、APT领跑区块链投资新趋势
阅读:18
-
什么霞是什么梗?揭秘网络热词霞的爆火真相,3秒get流行密码!
阅读:18
-
2026年最具潜力NFT与GameFi代币TOP10榜单
阅读:18
-
2026年全球加密货币市值排名:比特币BTC稳居榜首
阅读:18
-
"什么下笔是什么梗"解析:网络热词出处及爆火原因揭秘,看完秒懂!
阅读:18










