ES6 में शुरू की गई जावास्क्रिप्ट कक्षाएं, जावास्क्रिप्ट प्रोटोटाइप-आधारित वंशानुक्रम पर वाक्यात्मक चीनी हैं। कक्षाएं वास्तव में "विशेष कार्य" हैं। आप निम्न सिंटैक्स का उपयोग करके क्लास कीवर्ड का उपयोग करके जावास्क्रिप्ट में कक्षाएं परिभाषित कर सकते हैं -
class Person {
// Constructor for this class
constructor(name) {
this.name = name;
}
// an instance method on this class
displayName() {
console.log(this.name)
}
} यह अनिवार्य रूप से निम्नलिखित घोषणा के बराबर है -
let Person = function(name) {
this.name = name;
}
Person.prototype.displayName = function() {
console.log(this.name)
} इस वर्ग को वर्ग भाव के रूप में भी लिखा जा सकता है। उपरोक्त प्रारूप एक वर्ग घोषणा है। निम्न प्रारूप एक वर्ग अभिव्यक्ति है -
// Unnamed expression
let Person = class {
// Constructor for this class
constructor(name) {
this.name = name;
}
// an instance method on this class
displayName() {
console.log(this.name)
}
} कोई फर्क नहीं पड़ता कि आप ऊपर बताए अनुसार कक्षाओं को कैसे परिभाषित करते हैं, आप निम्नलिखित का उपयोग करके इन कक्षाओं के ऑब्जेक्ट बना सकते हैं -
उदाहरण
let John = new Person("John");
John.displayName(); आउटपुट
John
आप https://www.tutorialspoint.com/es6/es6_classes.htm पर JS क्लास और क्लास कीवर्ड के बारे में गहराई से पढ़ सकते हैं।