JavaScript 构造函数的继承是如何工作的

JavaScript 构造函数的继承是如何工作的

在这里,我们将讨论在JavaScript中继承构造函数。构造函数定义了一个对象将包含的属性的原型。使用构造函数,我们可以在传递所需参数后创建一个新对象。

继承先前定义的构造函数意味着在新定义的构造函数中使用先前定义函数的参数,并添加一些新的参数。为此,我们需要使用call() 函数,该函数允许我们在当前上下文中调用在其他地方定义的函数。

语法:

myFunction.call( this, property1, property2, ... , propertyN )

示例: 在这里,我们创建了一个“员工”构造函数。创建了一个新的“开发人员”构造函数,它将继承“员工”的基本属性,并包含一些新的属性。

JavaScript

function Employee(name, age, gender, id) { 
    this.name = name; 
    this.age = age; 
    this.gender = gender; 
    this.id = id; 
}; 
  
function Developer(name, age, gender, id,  
specialization) { 
  
    // Calling Employee constructor function 
    Employee.call(this, name, age, gender, id); 
  
    // Adding a new parameter 
    this.specialization = specialization; 
} 
console.log(Employee.prototype); 
console.log(Developer.prototype);

输出:

Object
constructor: ƒ Employee(name, age, gender, id)
[[Prototype]]: Object

Object
constructor: ƒ Developer(name, age, gender, id, specialization)
[[Prototype]]: Object

我们可以注意到,’Developer’构造函数继承了’Employee’构造函数的属性,同时还有一个新的参数’specialization’。在这里,我们使用call()函数调用Employee函数,以传递所需的参数给Employee构造函数。

在传递该对象的必需属性的值之后,我们还可以使用这些构造函数创建对象。

语法:

let Obj1 = new Object( parameters )

示例: 此示例描述了使用new关键字创建一个对象的实例的对象,该对象具有构造函数。

Javascript

function Employee(name, age, gender, id) { 
    this.name = name; 
    this.age = age; 
    this.gender = gender; 
    this.id = id; 
}; 
  
function Developer(name, age, gender, id, specialization) { 
  
    // Calling Employee constructor function 
    Employee.call(this, name, age, gender, id); 
  
    // Adding a new parameter 
    this.specialization = specialization; 
} 
  
// Creating objects 
let Employee1 = new Employee("Suraj", 28, "Male", 564); 
let Developer1 = new Developer("Karishma", 31, "Female", 345, 
    "Frontend Developer"); 
console.log(Employee1); 
console.log(Developer1);

输出:

Employee {name: 'Suraj', age: 28, gender: 'Male', id: 564}
age: 28
gender: "Male"
id: 564
name: "Suraj"
[[Prototype]]: Object

Developer {name: 'Karishma', age: 31, gender: 'Female', id: 345, 
    specialization: 'Frontend Developer'}
age: 31
gender: "Female"
id: 345
name: "Karishma"
specialization: "Frontend Developer"
[[Prototype]]: Object

我们可以观察到Employee的构造函数被继承,以创建一个新的构造函数Developer,可以用它来创建具有新属性的对象,同时也继承了父构造函数的属性。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程