Affiliate link
JavaScript - Classes/Objects
Objects
A JavaScript object is a collection of elements that can be a property or method. All JavaScript objects have a prototype.
Define JavaScript Object with object literal notation
var myObject = {
color: "Blue",
product: "Book",
display: function() {
return "Product: " + this.product + ", Color: " + this.color;
}
};Define JavaScript Object with object constructor
var myObject = new Object();
myObject.color = "Blue";
myObject.product = "Book";
myObject.display = function() {
return "Product: " + this.product + ", Color: " + this.color;
}Classes object
Class keyword is only supported from ECMAScript version 6. Alternatively, you can use object function to create a class.
Create class using Class keyword
class BookClass
class BookClass {
constructor() {
this.color = "Blue";
this.product = "Book";
}
function display() {
return "Product: " + this.product + ", Color: " + this.color;
}
}Class - constructor, extends, super
constructor, extends, and super
class Book {
constructor(color, product) {
this.color = color;
this.product = product;
}
function display() {
return "Product: " + this.product + ", Color: " + this.color;
}
}
class PythonBook extends Book {
constructor(publisher, color, product) {
super(color, product)
this.publisher = publisher;
}
function display() {
return "Publisher : " + this.publisher + ", Product: " + this.product +
", Color: " + this.color;
}
}
Create class using object function
function BookClass()
function BookClass() {
this.color = "Blue";
this.product = "Book";
this.display = function() {
return "Product: " + this.product + ", Color: " + this.color;
}
}
var myObject = new BookClass();
myObject.color = "Red";
myObject.display();Modify Object Prototype
Add a new property by modifying the prototype property.
BookClass.prototype.isAvailable = true;
function BookClass() {
this.color = "Blue";
this.product = "Book";
this.display = function() {
return "Product: " + this.product + ", Color: " + this.color;
}
}
var myObject = new BookClass();
BookClass.prototype.isAvailable = true;
console.log("myObject", myObject);Affiliate link
Affiliate link




