Table of Contents
Object —— Class
Object —— Prototype
Small exercise
Home Web Front-end JS Tutorial Learn more about Objects in JavaScript

Learn more about Objects in JavaScript

Jul 07, 2021 am 10:57 AM
javascript object object

Learn more about Objects in JavaScript

Here we continue to learn two more important types, which are Object and Symbol. We are mainly talking about Object. Compared to Object, Symbol is just a supporting role.

Everyone has been exposed to the concept of objects very early. In fact, people will have the abstraction of objects when they are about 5 years old. Many times we seem to think that objects are objects only when we learn programming. But from a cognitive perspective, it should be much earlier than our usual understanding of the value type in numbers. Therefore, from a historical perspective, it has always been evaluated that objects are closer to human natural thinking.

I just mentioned that we have had the concept of objects since childhood, so why do we say that we have it since childhood? Object actually means a very broad thing in English. It is any object, it can be an abstract object or a real object. But in our Chinese language, we cannot find a suitable word that can represent all things in Paul to express the meaning of Object. So in Chinese we just translate it directly into "object".

So this Chinese translated word has caused some misunderstandings about Object. Because object is in English, I think it is closer to the meaning of the word target. In fact, in Taiwan, Object is translated as "object". The word object is indeed more semantically relevant, but everyone is not particularly familiar with the word object, so it has evolved into a technical noun.

But no matter what, we should have such a concept in our minds. From childhood, we should know that we have three identical fish, but in fact they are three different objects. So why are the same fish different objects?

We can understand it this way, suddenly one day the tail of one of the fish was bitten off. I was surprised to find that the other two fish were not affected. Therefore, when we describe these three fish in the computer, they must be three sets of the same data objects, but three copies are stored separately and are independent of each other.

The difference between this kind of fish and fish is actually the embodiment of a characteristic of their objects. Some cognitive studies believe that when we are about 5 years old, we have the cognition of

. In fact, children today develop earlier, and at 5 years old they are already a The lowest age. When we are 2 to 3 years old, everyone knows that this apple is different from that apple. If you take a bite of this apple, the other apple will be fine.

So if we describe these three fishes in the computer, we must store the data in three separate copies, because it is the state of three objects, rather than the same one. The data is stored in three copies, but they happen to be equal. In fact, this is the basis of all object-oriented programming. In other words, if it is this fish, it is this fish. If it is not this fish, it is not this fish. It will not be different because of the change of the state of the object itself. .

So what is our understanding of objects?

Any object is unique, which has nothing to do with its own status. The status is determined by the object.

Even if two objects have the same status, they are not equal. . So sometimes we use objects as data, but this is actually a language usage skill, and it does not use objects as objects. For example, when we pass a config, in fact, the process of passing config does not actually treat objects as objects. Instead of transferring it, we use the object as a data carrier to transfer it. This time involves the deviation between our use of object types and the design purpose of the language itself.

We use states to describe objects. For example, we have an object "fish", and its state is whether it has a "tail" and "how big are its eyes." We will use these state values ​​to describe an object. .

The change of our state is both behavior and the change of state is that the fish’s tail is gone and has been bitten off. Then after a while it grew a new tail, and then the tail could swing back and forth. These are all changes in its status. And these changes in state are behaviors.

Object three elements

Learn more about Objects in JavaScript

Identifier——Unique identification
  • State——State
  • Behavior——Behavior
  • In fact, philosophers will study an Object, such as what is the unique identifier of a fish, and pick out all the bones of the fish to see if it is still the fish. Then cut off all the meat and put it together to see if it is the same fish. This is the famous philosophical question "
Ship of Theseus

". We don’t need to care about this, we just say that the variable has a unique identifier, which is also a core element of the object.

Objects must have a state, the state can be changed, and change is behavior. In this way, the three elements of the object are established.

Any concept in our minds and any object in reality can become an object, as long as the three elements are complete.

Object —— Class

First the Class class and the Type type are Two different concepts.

#An important way for us to understand objects is called classification. We can use classification to describe objects. For example, after we study and detect a fish, it has similar characteristics to all fish of the same type, so we can classify these fish into one category, called "Fish Class".

In fact, there is a larger classification of fish called "Animal", then there are other animal classifications under animals, such as sheep. Therefore, the commonality between fish and sheep will be described as "animal". Then we abstract layer by layer, and there will be Object on top of "Animal".

Category is a very common way to describe objects. For example, the organisms we just talked about, objects can be used to divide all organisms into phyla, orders, families, genera and species, which is a huge classification system. When writing code, the classification is to serve the business, and we do not need to divide it in such detail. Usually we will write the common needs in the code, and we will mention Animal, without distinguishing whether it is a mammal, an egg-laying animal, a chordate, etc. There are two schools in the

classification, one is categorization, and the other is category.

  • Classification——That is, we study a single object, and then we extract commonalities from it and turn them into classes. Then we extract commonalities between classes and turn them into into a higher abstract class. For example, we extract commonalities between "sheep" and "fish", and then extract the sharing between them into the class "animal". Multiple inheritance is a very natural thing for "categorization" methods, such as diamond inheritance, triangle inheritance, etc. in C.
  • Classification ——Abstract everything in the world into a base class Object, and then define what is in this Object. Computer languages ​​that adopt classification ideas have a single inheritance structure. And there will be a base class Object.

JavaScript is a language that is closer to the idea of ​​"classification", but it is not entirely the idea of ​​classification because it is a multi-paradigm object-oriented language.

Object —— Prototype

Next let’s talk about the way JavaScript describes objects.

In fact, Class Based Object is not the only way to understand objects. We have another one that is closer to human natural cognition. The ability to classify may not be available until at least elementary school. But after we get to know the object, we can almost immediately get another way to describe the object. That is "Prototype".

Prototype is actually understood by " Like a cat and draw a tiger". In fact, it is a prototype method used to follow a cat and draw a tiger. Because cats and tigers are very similar, we only need to distinguish the direct differences between them.

For example, if we want to study fish now, then we find a typical fish, such as a specific carp, and then we add all the characteristics of this carp to On the prototype. As long as other fish have objects, we will modify them based on the fish prototype. For example, catfish is more edible than carp, it eats meat, and its body is slippery, so we can add these characteristics to the prototype of carp, so that we can describe catfish.

So in the sheep category, we also selected a little sheep to be our basic prototype. Then if we find a goat, and we analyze that its characteristics are beards, bent feet, long, hard, and able to climb mountains, then we will add these characteristics to the prototype of the little sheep, and then we will describe A goat.

Then we also choose a typical animal among the superior "animals", such as a tiger, which has four hooves, but not all animals may have four hooves, but the prototype selection is relatively easy It is relatively free. For example, if we choose a snake as the prototype of an animal, then we will have a lot of effort when describing a fish, and even more effort when describing a cat.

There will also be a final prototype in the prototype called Object Prototype. This is the typical item of all items, and can also be said to be the ancestor of all our objects. We describe any object in terms of its difference from the object being described.

Generally speaking, there will be no prototype on top of Object Prototype, but some languages ​​will allow a Nihilo prototype. Nihilo means nothingness and emptiness, which is a language-neutral way of speaking. If we use the specific facilities of JavaScript to describe, then the Nihilo prototype is null, which is easy for everyone to understand, and we can easily create a null The prototype of the object.

Small summary:

  • Our prototype is a method of describing objects that is closer to human original cognition
  • So various object-oriented methods In fact, there is no absolute right or wrong, there are only different costs in different scenarios.
  • The cognitive cost of prototypes is low, and the cost of making the wrong choice is also relatively low, so prototypes are suitable for things that are not so clear and are relatively free in description. Scenarios
  • Classification (Class) is more suitable for use in some more rigorous scenarios, and Class has an advantage. It is naturally integrated with the type system, so many languages ​​​​will choose to use Class The inheritance relationship is integrated into the inheritance relationship of the type system

Small exercise

If we need to write a "dog bites man" Class, How do we need to design it?

If we follow a relatively simple method, we will define a Dog Class, and then give this Class a bite method.

class Dog {
  bite(Human) {
    // ......
  }
}
Copy after login

Such a piece of code is exactly the same as our question, but this abstraction is a wrong abstraction. Because this violates the basic characteristics of object-oriented, no matter how we design it, it is wrong as long as this bite happens to dogs.

Why?

#Because we talked about the three elements of object-oriented before, the state of the object must be changed by the behavior of the object itself. So if we write the action bite in the dog's Class, but the changed state is "human", after the dog bites a human, it will only cause harm to the human. Therefore, the state of "human" changes in this behavior, so if the behavior is in the dog's Class, it violates the object-oriented characteristics.

Of course, if it is a dog eating a human, then we can barely establish it, because the dog will be full after eating the human, and the dog's state will be changed. But when a dog bites a person, we can basically think that this behavior does not change the dog's state in any way.

So we should design a behavior in the "person" Class. Then some students will ask, should we add a biteBy behavior to people? Is it just an act of being bitten? It doesn't seem right, because the behavior in the person Class should be used to change the person's state. So what should be the name of this behavior?

The more reasonable behavior here should be hurt to indicate being hurt, and then the parameter passed into this behavior is the degree of damage damage. Because people here only care about the amount of damage it suffered, and they don’t need to care whether it was a dog bite or something else.

class Human {
  hurt(damage) {
    //......
  }
}
Copy after login

In the actual development scenario, dog bites human, it is a business logic. We only need to design the behavior that changes the state inside the human Human object, so its correct name should be hurt. The damage here can be an object calculated or generated from the behavior method of the dog Class bitebite, but if we directly pass the dogDog If an object comes in, it will definitely not comply with our abstract principles for objects.

Finally our code implementation logic is as follows:

class Human {
  constructor(name = '人') {
    this.name = name;
    this.hp = 100;
  }

  hurt(damage) {
    this.hp -= damage;
    console.log(`${this.name} 受到了 ${damage} 点伤害,剩余生命中为 ${this.hp}`);
  }
}

class Dog {
  constructor(name = '狗') {
    this.name = name;
    this.attackPower = 10; // 攻击力
  }

  bite() {
    return this.attackPower;
  }
}

let human = new Human('三钻');
let dog = new Dog();

human.hurt(dog.bite()); // 输出:三钻 受到了 10 点伤害,剩余生命中为 90
Copy after login

Principles of designing objects:

  • We should not be described by language interference (especially interference from business requirements)
  • When designing the state and behavior of objects, we always follow the principle of "Behavior changes state"
  • Violation of With this principle, the cohesion of the entire object will be lost, which will cause huge damage to the architecture

For more programming-related knowledge, please visit:Introduction to Programming! !

The above is the detailed content of Learn more about Objects 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

How do PHP functions return objects? How do PHP functions return objects? Apr 10, 2024 pm 03:18 PM

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

What should I pay attention to when a C++ function returns an object? What should I pay attention to when a C++ function returns an object? Apr 19, 2024 pm 12:15 PM

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

Analyze the differences between heap and stack in Java and their application scenarios Analyze the differences between heap and stack in Java and their application scenarios Feb 24, 2024 pm 11:12 PM

The difference between Java heap and stack and application scenario analysis require specific code examples. In Java programs, heap and stack are two commonly used data structures, and they assume different roles and functions in memory. Understanding the difference between heap and stack is crucial to writing efficient Java programs. First, let's take a look at the Java heap. The heap is an area used to store objects. All objects created in the program are stored in the heap. The heap is where memory is dynamically allocated and released while the program is running. It is not subject to any restrictions and can be automatically allocated and released as needed.

See all articles