JavaScript 建構函式中的繼承是如何工作的?
在本文中,我們將討論 JavaScript 中繼承是如何工作的,以及如何在 JavaScript 的建構函式中使用此面向物件程式設計特性。
我們還將簡要介紹 JavaScript 中的原型物件。因此,非常感謝您事先了解相關知識。
在 JavaScript 中,繼承是一種機制,物件可以透過它繼承另一個物件屬性和方法。這可以透過使用建構函式和原型屬性來實現。
建立建構函式時,可以使用原型屬性將屬性和方法新增到建構函式的原型物件中。然後,使用建構函式建立的任何物件都將繼承這些屬性和方法。
示例
讓我們藉助以下示例來理解這一點:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.getName = function() {
return this.name;
};
在此示例中,Person 建構函式具有 name 和 age 屬性以及 getName 方法。使用 Person 建構函式建立的任何物件都將繼承原型中的這些屬性和方法。
您還可以建立一個新的建構函式,透過使用 call 或 apply 方法呼叫父建構函式並將 this 作為第一個引數傳遞,從而繼承自現有的建構函式。
示例
以下是 JavaScript 中正在工作的繼承完整示例:
// Parent constructor function
function Person(name, age) {
this.name = name;
this.age = age;
}
// Adding a method to the prototype
Person.prototype.getName = function() {
return this.name;
};
// Child constructor function
function Employee(name, age, company) {
// Calling the parent constructor function
Person.call(this, name, age);
this.company = company;
}
// Setting the prototype of the child constructor function
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
// Adding a method to the child constructor function
Employee.prototype.getCompany = function() {
return this.company;
};
const employee1 = new Employee("John", 25, "Google");
console.log(employee1.name); // "John"
console.log(employee1.age); // 25
console.log(employee1.getName()); // "John"
console.log(employee1.getCompany()); // "Google"
在此示例中,我們有一個名為 Person 的父建構函式,它接收 name 和 age 引數,它還有一個名為 getName() 的方法,該方法新增到 Person 建構函式的原型中。然後,我們有一個名為 Employee 的子建構函式,它繼承自 Person 建構函式的屬性和方法。Employee 建構函式接收一個額外的 company 引數,並且它還有一個名為 getCompany() 的方法,該方法新增到 Employee 建構函式的原型中。
因此,總的來說,在 JavaScript 中,建構函式可以用來建立繼承自父物件屬性和方法的物件,這可以透過將屬性和方法新增到建構函式的原型物件中,或者透過建立一個繼承自現有建構函式的新建構函式來實現。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP