使用apply方法实现JavaScript对象继承

作者:闭包旅人

时间:2026-10-27

浏览:200

本文介绍如何利用JavaScript的apply方法实现对象继承。通过Parent.apply(this, arguments)将父构造函数中的属性和方法绑定到子对象,从而复用父类逻辑。示例展示了如何定义父类和子类,并通过apply传递参数实现属性共享,同时保留子类特有方法。

文章目录
child.sayHello();

使用apply方法实现JavaScript对象继承

代码如下:

 
<script type="text/javascript">
// 使用apply方法实现对象继承
function Parent(username) {
this.username = username;
this.sayHello = function() {
alert(this.username);
} 
} 
}
function Child(username, password) {
Parent.apply(this, new Array(username));
// 效果等同于:
// Parent.apply(this, [username]);
this.password = password;
this.sayWorld = function() {
} 
} 
alert(this.password);
var child = new Child("lisi", "123");
}
var parent = new Parent("zhangsan");
var child = new Child("lisi", "123");
parent.sayHello();

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章