Learn more about Objects in JavaScript

青灯夜游
Release: 2021-07-15 20:01:59
forward
3417 people have browsed it

Learn more about Objects in JavaScript

Here we continue to learn two more important types, which areObjectandSymbol. 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 theClassclass and theTypetype 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 iscategorization, and the other iscategory.

  • 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 toOn 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 calledObject 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 ofObject Prototype, but some languages will allow aNihiloprototype. Nihilo means nothingness and emptiness, which is a language-neutral way of speaking. If we use the specific facilities of JavaScript to describe, then theNihiloprototype isnull, which is easy for everyone to understand, and we can easily create anullThe 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 aDogClass, and then give this Class abitemethod.

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 thisbitehappens 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 actionbitein 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 abiteBybehavior 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 behurtto indicate being hurt, and then the parameter passed into this behavior is the degree of damagedamage. 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 humanHumanobject, so its correct name should behurt. Thedamagehere can be an object calculated or generated from the behavior method of the dog Class bitebite, but if we directly pass the dogDogIf 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!

Related labels:
source:csdn.net
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!