Object-oriented JavaScript It is common in programming to create many objects of the same type. Object-oriented programming encapsulates properties and methods into classes. Functionality can be reused by creating new child classes.
Prototypes Every JavaScript object comes with a built-in variable called a prototype. Any properties or functions added to the prototype object will be accessible to a child object. A child object is created as an instance of the parent object using the keyword “new”.
Properties Type Sensor
ROBOT CLASS
Class inheritance In JavaScript, an object can be declared as an instance of the class, and it will inherit all the properties and methods belonging to that class. Here, the properties and methods for the class Robot can be inherited by each of its child objects.
let parentObject = function() { Creates a new child object as an instance of the parent object
let childObject = new parentObject();
Functions Just as in prototypes, an object can be declared as an instance of a function with the new command. This command acts as a constructor (a method used for initializing the properties of the class). The child object inherits all the properties and methods defined in the function.
Sets the child object’s title property
childObject.title = "ABC";
parentObject.prototype.getTitle = function(){ return this.title; Adds a new method to the parent object’s prototype
} Calls the method in the parent object’s prototype from the child object, and returns the child object’s “title” property, ABC
Creates a new parent object
this.title = "123"; }
Methods Sense() Move()
console.log(childObject.getTitle());
function Book(title, numberOfPages) { this.title = title; this.numberOfPages = numberOfPages; }; let JaneEyre = new Book("Jane Eyre", 200) console.log(JaneEyre.title);
Instantiates the new book Properties and methods of the function