JavaScript 中的 super 关键字?
在本文中,我们将讨论 JavaScript 中的 super 关键字并提供相应的示例。
super 关键字主要用于面向对象编程。super 关键字用于调用对象父类的参数和函数。
有时,父类和子类可能具有相同的函数名和参数名。在这种情况下,为了避免父类和子类函数名或参数名之间的混淆,使用super关键字。为了使用super关键字,子类方法必须扩展父类方法。
语法
super关键字的语法如下:
Super(arguments); // To call Super class arguments Super.Parent_Method(arguments) // To call super class methods.
其中,
arguments 是父类或父类方法的参数。
Parent_Method 是超类方法。
示例 1
这是一个示例程序,通过调用超类参数来定义super关键字的用法。
<!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>Super keyword in Javascript</title>
</head>
<body>
<p id="super" style="text-align : center"></p>
<script>
class Person{
constructor(person_name) {
this.name = person_name;
}
getPersonName() {
return this.name;
}
}
class Aadhar extends Person {
constructor(person_name,AadharID){
super(person_name);
this.AadharID = AadharID;
}
showAadharId() {
return 'The Aadhar ID for the person '+ this.getPersonName() +' is : '+this.AadharID;
}
}
var person_id = new Aadhar('Rajesh','5000 0000 0000 0000');
document.write(person_id.showAadharId());
</script>
</body>
</html>
执行上述代码后,将生成以下输出。
示例 2
这是一个示例程序,通过调用超类方法来定义super关键字的用法。
<!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>Super keyword in Javascript</title>
</head>
<body>
<p id="super" style="text-align : center"></p>
<script>
class Person{
constructor(person_name) {
this.name = person_name;
}
getPersonName() {
return 'The person name is : '+this.name;
}
}
class Aadhar extends Person {
constructor(person_name,PANID){
super(person_name);
this.PANID = PANID;
}
show_PAN_CARD_ID() {
return super.getPersonName() +' and the PAN Card ID is : '+this.PANID;
}
}
var person_id = new Aadhar('Ravi','DD JJN 7854 A');
document.getElementById('super').innerHTML = person_id.show_PAN_CARD_ID();
</script>
</body>
</html>
执行上述代码后,将生成以下输出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP