JavaScript 通过原型链和构造函数实现继承。使用原型链,父对象作为子对象的原型,子对象继承父对象的属性和方法。使用构造函数,子构造函数将父构造函数作为原型,并通过覆盖父类方法实现定制化。本例中,Person 是父类,Employee 是子类,Employee 继承了 Person 的属性和方法,并添加了自己的 sayJob 方法。

在原生 JavaScript 中实现继承
JavaScript 是一种基于原型链的语言,它不直接支持类和继承,但是可以通过使用原型链和构造函数来模拟继承。
使用原型链实现继承
<code class="js">const Parent = {
name: "Parent",
sayName() {
console.log(this.name);
}
};</code><code class="js">const Child = Object.create(Parent); Child.name = "Child";</code>
使用构造函数实现继承
<code class="js">function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};</code><code class="js">function Child(name) {
Parent.call(this, name);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;</code>在子类中覆盖父类方法
要覆盖父类中的方法,可以在子类的原型链中重新定义该方法。
<code class="js">Child.prototype.sayName = function() {
console.log("Child: " + this.name);
};</code>示例
以下是一个使用构造函数实现继承的示例:
<code class="js">function Person(name) {
this.name = name;
}
Person.prototype.sayName = function() {
console.log(this.name);
};
function Employee(name, title) {
Person.call(this, name);
this.title = title;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.sayJob = function() {
console.log(this.name + " is a " + this.title);
};
const john = new Employee("John", "Software Engineer");
john.sayName(); // 输出:"John"
john.sayJob(); // 输出:"John is a Software Engineer"</code>以上就是原生js如何实现继承的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号