Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

คีย์เวิร์ด Super ใน JavaScript

Super

Super Keyword ใช้เข้าถึงและเรียก Functions บน Parent Object ของ Object นิพจน์ super.prop และ super[expr] ใช้ได้ใน Method Definition ใดๆ ทั้งใน Classes และ Object Literals ใช้ใน Class "Extended" ที่ใช้คีย์เวิร์ด "extends"

Syntax

super(arguments);

ตัวอย่าง

ในตัวอย่างนี้ ลักษณะของ Class "Person" ถูก Extend ไปยัง Class "Student" ทั้งสอง Class มี Unique Properties ใช้ "super" เข้าถึง Property จาก Parent Class (Person) ไปยัง Extended Class (Student) ในขณะที่ "this" ใช้เข้าถึง Property ของ Extended Class เอง

<html> <body> <script>    class Person {       constructor(name, grade) {          this.name = name;          this.grade = grade;       }       goal() {          return `${this.name} wants to become a crickter!`;       }       interest() {          return `${this.name} interested in cricket !`;       }    }    class Student extends Person {       constructor(name, grade) {          super(name, grade);       }       need() {          return `${this.name} needs a cricket kit`;       }       career() {          return `${super.interest()}          ${super.goal()}          ${this.need()}`;       }    }    const student = new Student('Rishab pant', '7');    document.write(student.career()); </script> </body> </html>

ผลลัพธ์

Rishab pant interested in cricket ! Rishab pant wants to become a crickter! Rishab pant needs a cricket kit