Home Web Front-end Front-end Q&A How to write oop in javascript

How to write oop in javascript

May 16, 2023 am 09:43 AM

In Web development, JavaScript has become a very popular programming language. In JavaScript, object-oriented programming (OOP) is an important concept. Using OOP, you can structure your code and reduce its duplication, making it easier to maintain and extend. This article will introduce how to write OOP in JavaScript.

  1. Prototype (prototype) and constructor (constructor)

In JavaScript, the properties and methods of an object can be shared through prototypes, and constructors are used to Create a new object and initialize its properties. The following is a simple example using constructors and prototypes:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.sayHi = function() {
  console.log("Hi, my name is " + this.name + " and I'm " + this.age + " years old.");
}

var person1 = new Person("John", 30);
var person2 = new Person("Mary", 25);

person1.sayHi(); // Hi, my name is John and I'm 30 years old.
person2.sayHi(); // Hi, my name is Mary and I'm 25 years old.
Copy after login

In the above example, we define a Person constructor that initializes name and ageProperties. Then, we use Person.prototype to add a sayHi method to each Person object. This method can be shared by all Person objects. . Finally, we created two Person objects and called their sayHi methods.

  1. Class(class)

In ES6, JavaScript introduced the concept of class and used the keyword class to implement it. Classes provide a cleaner, easier-to-understand syntax for defining objects.

The following is an example of using classes:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  sayHi() {
    console.log("Hi, my name is " + this.name + " and I'm " + this.age + " years old.");
  }
}

let person1 = new Person("John", 30);
let person2 = new Person("Mary", 25);

person1.sayHi(); // Hi, my name is John and I'm 30 years old.
person2.sayHi(); // Hi, my name is Mary and I'm 25 years old.
Copy after login

In the above example, we use the class keyword to define a Person class, And the name and age properties are initialized in the constructor method. Then, we defined a sayHi method to output a greeting. Finally, we created two Person objects and called their sayHi methods.

  1. Inheritance

In OOP, inheritance refers to deriving a new object from an existing object. The new object inherits the original object. properties and methods. In JavaScript, inheritance can be achieved by using prototype and class.

The following is an example of using prototype to implement inheritance:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.sayHi = function () {
  console.log("Hi, my name is " + this.name + " and I'm " + this.age + " years old.");
}

function Student(name, age, major) {
  Person.call(this, name, age);
  this.major = major;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.sayMajor = function() {
  console.log("My major is " + this.major + ".");
}

let person1 = new Person("John", 30);
let student1 = new Student("Mary", 25, "Computer Science");

person1.sayHi(); // Hi, my name is John and I'm 30 years old.
student1.sayHi(); // Hi, my name is Mary and I'm 25 years old.
student1.sayMajor(); // My major is Computer Science.
Copy after login

In the above example, we define a Person constructor, in the prototype Added sayHi method. In addition, we defined a Student constructor and called the Person constructor using the call method to initialize name and age attribute, and added a major attribute. We then create a copy of Person.prototype using the Object.create method and assign it to Student.prototype so that StudentObjects can inherit the properties and methods of Person objects. Finally, we define a sayMajor method to output the student's major. Finally, we created a Person object and a Student object and called their methods.

The following is an example of using class to implement inheritance:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  sayHi() {
    console.log("Hi, my name is " + this.name + " and I'm " + this.age + " years old.")
  }
}

class Student extends Person {
  constructor(name, age, major) {
    super(name, age);
    this.major = major;
  }
  
  sayMajor() {
    console.log("My major is " + this.major + ".");
  }
}

let person1 = new Person("John", 30);
let student1 = new Student("Mary", 25, "Computer Science");

person1.sayHi(); // Hi, my name is John and I'm 30 years old.
student1.sayHi(); // Hi, my name is Mary and I'm 25 years old.
student1.sayMajor(); // My major is Computer Science.
Copy after login

In the above example, we define a Person class, in ## The name and age properties are initialized in the #constructor method, and a greeting is output in the sayHi method. Then, we created a Student class using the extends keyword and called the of the Person class using the super keyword constructor method to initialize the name and age properties, and add a major property. Finally, we define a sayMajor method to output the student's major. Finally, we created a Person object and a Student object and called their methods.

Conclusion:

In JavaScript, OOP is a very important concept. Using objects, constructors, prototypes, and classes can better organize code and reduce duplication. Inheritance can be achieved through prototypes and classes. Starting with ES6, JavaScript introduced the keyword

class, which provides a simpler and easier-to-understand syntax for defining objects. Whenever possible, it is important to choose the right approach for writing OOP code as this will yield significant benefits in project development and maintenance.

The above is the detailed content of How to write oop in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is useEffect? How do you use it to perform side effects? What is useEffect? How do you use it to perform side effects? Mar 19, 2025 pm 03:58 PM

The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.

How does currying work in JavaScript, and what are its benefits? How does currying work in JavaScript, and what are its benefits? Mar 18, 2025 pm 01:45 PM

The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read

How does the React reconciliation algorithm work? How does the React reconciliation algorithm work? Mar 18, 2025 pm 01:58 PM

The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159

What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code? What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code? Mar 18, 2025 pm 01:44 PM

Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.

How do you connect React components to the Redux store using connect()? How do you connect React components to the Redux store using connect()? Mar 21, 2025 pm 06:23 PM

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

What is useContext? How do you use it to share state between components? What is useContext? How do you use it to share state between components? Mar 19, 2025 pm 03:59 PM

The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.

How do you prevent default behavior in event handlers? How do you prevent default behavior in event handlers? Mar 19, 2025 pm 04:10 PM

Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.

What are the advantages and disadvantages of controlled and uncontrolled components? What are the advantages and disadvantages of controlled and uncontrolled components? Mar 19, 2025 pm 04:16 PM

The article discusses the advantages and disadvantages of controlled and uncontrolled components in React, focusing on aspects like predictability, performance, and use cases. It advises on factors to consider when choosing between them.

See all articles