Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use JavaScript for object-oriented programming

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "how to use JavaScript for object-oriented programming", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use JavaScript for object-oriented programming" this article.

1. Objects, properties, methods

1.1 object literals (Objectliteral)

Set the property in curly braces to create a new object in JavaScript. The value of the object literal property can be any data type, such as a function numeric quantity, array, string, number, or Boolean value.

Let's create an object for a named book whose properties include author, year of publication, title, and method.

-summary. Constbook = {title: "Hippie", author: "Paulo Coelho", year: "2018"}

After the object is created, you can use dotted notation to get the value. For example, you can use book.title. Gets the value of the title, and you can also access the property using square brackets book ['title'].

1.2 object constructor (Objectconstructor)

The object constructor is the same as the regular function. It is used every time an object is created. You can use it with new keywords. Object constructors are useful when you need to create multiple objects with the same properties and methods.

Constbook = {title: "Hippie", author: "Paulo Coelho", year: "2018"} const book1 = {title: "The Alchemist", author: "Paulo Coelho", year: "1988",}

If you want to create multiple book objects, you must copy the code for each book. You can continue to create book objects, but this is a bit troublesome-- but the object constructor helps to use the object literals again.

FunctionBook (title, author, year) {this.title = title; this.author = author; this.year = year;} const book1 = new Book ('Hippie',' Paulo Coelho', '2018'); console.log (book1) > Book {title: "Hippie", author: "Paulo Coelho", year: "2018"} / / if we want to create more than onebook just we call function book with new keyword.const book2 = new Book ('TheAlchemist',' Paulo Coelho', '1988')

Book1 and book2 create an instance of Book and assign it to variables. Want to know whether one object is an instance of another. You can use instanceof.

Book1 instanceof Book > true

1.3 Object.create () method

Each object in JavaScript will be created from the master object. Any time you use the capital letter "O", it refers to the primary object. We can print the master object in the console console. The main object has many methods, so let's take a look at the object.create () method.

The Object.create () creation method uses existing objects as prototypes to create new objects. The basic syntax is as follows:

Object.create (proto, [propertiesObject])

Proto is the prototype of the newly created object. PropertiesObject is an option.

Here's a simple example:

ConstBook = {summary: function () {console.log (`${this.title} iswritten by ${this.author}.`)} const book1 = Object.create (Book); book1.author = "Paulo Coelho"; book1.title = "Hippie"; console.log (book1.summary ()); > Hippie iswritten by Paulo Coelho.

The above example creates a raw object, book1, and assigns values to the author and title. You can see the summary function in the original object:

The Object.create () method is described in detail below.

two。 Class

A class is not an object, it is the blueprint of an object and a special function. You can define a function using its expressions and declarations, or you can define a class in this way. Blueprints can be used to represent the number of objects.

You can use the keywords and names of the class. The syntax is similar to Java.

Class syntax is a good way to use object-oriented programming and manage prototypes:

Let Book= function (name) {this.name = name} let newBook = function (name) {Book.call (this, name)} newBook.prototype = Object.create (Book.prototype); const book1 = new newBook ("The Alchemist")

This example uses the ES6 class syntax:

ClassBook {constructor (name) {this.name = name}} class newBook extends Book {constructor (name) {super (name);}} const book1 = new newBook ("The Alchemist")

The class syntax is syntactic syntactical sugar-and it still uses a prototype-based model behind the scenario. A class is a function, and a function is an object in JavaScript.

ClassBook {constructor (title, author) {this.title = title; this.author = author;} summary () {console.log (`${this.title} writtenby ${this.author}`);} const book1 = new Book ("", "); console.log (typeof Book); >" function "console.log (typeof book1); >" object "3. Encapsulation (Encapsulation)

Encapsulation means to hide information or data. An object performs its function without revealing any execution details to an external user. In other words, its private variables are only visible to the current function and are not accessible to the global scope or other functions.

ConstBook = function (t, a) {let title = t; let author = a; return {summary: function () {console.log (`${title} written by$ {author}.`);} const book1 = new Book ('Hippie',' Paulo Coelho'); book1.summary (); > Hippie written by Paulo Coelho.

In the above code, the title and author are visible only within the scope of the function Book, and the method summary is visible to the user of Book. So the title and author are encapsulated in Book.

4. Abstract

Abstraction means hiding. It is a way to hide implementation details, showing only the basic features to the user. In other words, it hides irrelevant details and only shows what must be shown to the outside world. Lack of abstraction can lead to maintainability problems in the code.

ConstBook = function (getTitle, getAuthor) {/ / Private variables / properties let title = getTitle; let author = getAuthor;// Publicmethod this.giveTitle = function () {return title;} / / Private method const summary = function () {return `${title} written by$ {author}.`} / / Publicmethod that has access toprivate method. This.giveSummary = function () {return summary ()} const book1 = new Book ('Hippie',' Paulo Coelho'); book1.giveTitle (); > "Hippie" book1.summary (); > Uncaught TypeError: book1.summary is not a functionbook1.giveSummary (); > "Hippie written by Paulo Coelho." 5. Reuse / inheritance

JavaScript inheritance is a mechanism that allows us to create a new class using an existing class. That is, the subclass inherits all the properties and behaviors of the parent class.

Generally, JavaScript is not a class-based language. The keyword "class" is introduced in ES6, but it is syntactic sugar, and JavaScript is still prototype-based. In JavaScript, inheritance is achieved through the use of prototypes. This pattern is called behavioral delegation pattern or prototype inheritance.

This can also be demonstrated by the book example:

FunctionBook (title, author, year) {this.title = title; this.author = author; this.year = year; this.summary = function () {console.log (`${this.title} iswritten by ${this.author}.`)} const book1 = newBook ('Hippie',' Paulo Coelho', '2018'); const book2 = newBook (' The Alchemist', 'Paulo Coelho',' 1988')

Prototype inheritance

For each instance of Book, we are rebuilding memory for the methods in the base class. These methods must be shared across all instances-they should not be specific to individual instances. The prototype in the figure is:

LetCorebook = function (title) {this.title = title} Corebook.prototype.title = function () {console.log (`name of the book is$ {this.title} `);} Corebook.prototype.summary = function (author) {console.log (` ${this.title} is writtenby ${this.author} `);} let Book = function (title, author) {Corebook.call (this, title, author)} Book.prototype = Object.create (Corebook.prototype) Let book1 = new Book ('TheAlchemist',' Paulo Coelho'); book1.title (); > name of the book is The Alchemistbook1.summary (); > TheAlchemist is written by Paulo Coelho

In the above code, the instance of Book has a copy of the prototype that can be linked to the prototype of Book, while the prototype of Book is linked to the prototype of Corebook.

6. Polymorphisms

The ability to use the same method on different objects and let each object have its own form or form is called polymorphism.

Letbook1 = function () {} book1.prototype.summary = function () {return "summary of book1"} let book2 = function () {} book2.prototype = Object.create (book1.prototype); book2.prototype.summary = function () {return "summary of book2"} let book3 = function () {} book3.prototype = Object.create (book1.prototype) Book3.prototype.summary = function () {return "summary of book3"} var books = [new book1 (), new book2 (), new book3 ()]; books.forEach (function (book) {console.log (book.summary ());}); > summary of book1 > summary of book2 > summary of book3

The relationships between objects will be defined by association, aggregation, and composition.

7. Association

An association is a relationship between two or more objects. Each object is independent. In other words, associations define multiplicity between objects: one-to-one, one-to-many, many-to-one, and many-to-many.

FunctionBook (title, author) {this.title = title; this.author = author;} const book1 = new Book ('Hippie',' Paulo Coelho'); const book2 = new Book ('TheAlchemist',' Paulo Coelho'); book2.multiplicity = book1

Book1 assigns a variety of attributes to book2, showing the relationship between objects book1 and book2. Both can be added and deleted independently.

8. Polymerization

Aggregation is a special case of association. In the relationship between two objects, one object may be more important than the other. In other words, when one object has more ownership than another, this is aggregation. The object owner is often referred to as aggregation and is called a component by the owner. Aggregation is also called "Has-a" relationship.

FunctionBook (title, author) {this.title = title; this.author = author;} const book1 = new Book ('Hippie',' Paulo Coelho'); const book2 = new Book ('TheAlchemist',' Paulo Coelho'); let publication = {"name": "new publicationInc", "books": []} publication.books.push (book1); publication.books.push (book2)

Book1 and book2 are added to the books under the object publication. If you delete publication after book1 and book2 are running, both Book and publication will run independently.

9. Combination

Combination is a special case of aggregation. One object contains another object, and the contained object cannot survive without it.

Let Book= {"title": "TheAlchemist", "author": "PauloCoelho", "publication": {"name": "newpublication Inc", "address": "chennai"}}

There are strict restrictions on the properties publication and Book objects, and publication cannot do without Book objects. If the id of the Book is deleted, the publication will also be deleted.

Reorganization and light inheritance

Inheritance refers to the situation in which one object is based on another. For example, book1 inherits the properties and methods of books such as title, author, and conclusion, so it establishes a book1 is-a Book relationship.

Composition is to collect single objects and combine them to build more complex objects. To build book1, you need some methods, such as paper and pen. So the book1 has-a paper and a pen relationship emerges.

ConstgetTitle = (data) = > ({title: () = > console.log (`booksummary need to: ${data.title} `)}); const getAuthor = (data) = > ({author: () = > console.log (`author:$ {data.author}`)}); const getSummary = () = > ({summary: () = > console.log (`booksummary need to update.`)}) Const Book = (title, author) = > {const data = {title, author} return Object.assign ({}, getTitle (data), getAuthor (data), getSummary ())} let book1 = Book ('The Alchemist',' Paulo Coelho'); book1.title (); > "title: The Alchemist" are all the contents of the article "how to use JavaScript for object-oriented programming". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report