除了 JavaScript 类中的构造函数之外,还有其他方法吗?
在这篇文章中,我们将学习除了 JavaScript 类中的构造函数之外的另一种方法,并提供相应的 JavaScript 示例。
构造函数用于创建和初始化类的实例,即对象。构造函数的作用是构建一个新对象并为对象上已存在的任何属性设置值。每个类都有一个默认构造函数。如果我们不提供自己的构造函数,则将调用默认构造函数。
让我们通过本文后面提供的合适示例来更好地理解这个概念。
语法
构造函数的语法如下:
Constructor(); // No parameters Constructor(param1); //One parameter constructor Constructor(param1,param2,…,paramN) // N-parameter constructor.
Param1、param2、…paramN 是传递给构造函数的参数。
示例 1
这是一个编写除了构造函数之外的方法的示例程序。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Another method other than a constructor in a JavaScript class</title>
</head>
<body style="text-align: center ;">
<p> Another method other than a constructor in a JavaScript class </p>
<p id="method"></p>
<script>
class Person {
constructor(name){
this.name = name;
}
PersonName() {
return 'The person name is : '+this.name;
}
}
person_1 = new Person("Raghu");
document.getElementById("method").innerHTML = person_1.PersonName();
</script>
</body>
</html>
执行上述代码后,将生成以下输出。
示例 2
这是一个说明除了构造函数之外的方法用法的示例程序。我们使用了一个名为 PersonDetails() 的用户定义方法来进行初始化,而不是使用默认构造函数。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Another method other than a constructor in a JavaScript class</title>
</head>
<body style="text-align: center ;">
<p> Another method other than a constructor in a JavaScript class </p>
<p id="method"></p>
<script>
class Person {
constructor(name, EmployeeID, designation) {
this.name = name;
this.EmployeeID = EmployeeID;
this.designation = designation;
}
PersonDetails() {
return this.name + " has the designation : " + this.designation;
}
}
person_1 = new Person("Rajesh", "10023", "Software Engineer");
document.getElementById("method").innerHTML = person_1.PersonDetails();
</script>
</body>
</html>
执行上述代码后,将生成以下输出。
示例 3
在下面的示例中,属性实际上是在一个名为“anotherMet()”的用户给定方法中初始化的,而不是使用默认方法 constructor()。通过此方法,实际结果在输出中执行,如所示。
<html>
<body>
<p id="method"></p>
<script>
class Company {
constructor(branch) {
this.name = branch;
}
anotherMet(x) {
return x + " is the head of " + this.name;
}
}
myComp = new Company("Microsoft.");
document.getElementById("method").innerHTML = myComp.anotherMet("Bill gates");
</script>
</body>
</html>
执行上述代码后,将生成以下输出。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP