Make Money Online HTML PHP JAVASCRIPT Object-oriented Programming in JavaScript: Made Super Simple | Mosh

Object-oriented Programming in JavaScript: Made Super Simple | Mosh

Object-oriented Programming in JavaScript: Made Super Simple | Mosh post thumbnail image


Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which are data structures that contain data fields and methods. In OOP, data fields and methods are bundled into a single unit, which is called an object.

JavaScript is a versatile language that supports various programming paradigms, including OOP. In this article, I’ll show you how to create objects in JavaScript and use them to write simple programs.

To create an object in JavaScript, you use the keyword new followed by the name of the object. The name of the object is followed by a pair of parentheses, which contain the object’s data fields and methods.

For example, the following code creates an object called person :

var person = new Object();

The person object has two data fields: firstName and lastName . It also has a method called sayHello() , which prints the string “Hello, my name is ” followed by the firstName and lastName data fields.

person.sayHello = function() {

console.log(“Hello, my name is ” + this.firstName + ” ” + this.lastName);

};

You can access the data fields and methods of an object by using the dot operator ( . ). For example, the following code prints the firstName and lastName data fields of the person object:

console.log(“First name: ” + person.firstName + ” Last name: ” + person.lastName);

You can also call the sayHello() method of the person object by using the following code:

person.sayHello();

The following code demonstrates how to create a simple program that uses objects. The program asks the user to enter their first and last name, and then prints a message that says “Hello, ” followed by the user’s first name and last name.

var person = new Object();

person.firstName = “”;

person.lastName = “”;

console.log(“Please enter your first and last name:”);

var input = document.getElementById(“input”).value;

person.firstName = input.substring(0, input.indexOf(” “));

person.lastName = input.substring(input.indexOf(” “) + 1);

Related Post