JavaScriptcolumn introduces the objects of JavaScript and gives you a new understanding.
Here we continue to learn two more important types, which areObject
andSymbol
. 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?
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 ofWe 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.
. 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.
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. Still not this 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.
First
Class
class andType
Types 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.
Next let’s talk about how JavaScript describes objects Way.
In fact, Class Based Object is not the only way to understand objects. We have another method that is closer to human natural cognition. of. 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 need to find a typical fish, such as a specific carp, and then we add all the characteristics of this carp to thefishprototype. 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 aNihilo
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 theNihilo
prototype isnull
, which is easy for everyone to understand, and we can easily create anull
The prototype of the object.
##Small exercise If we need to write How do we design a "dog bites" Class? If we follow a relatively simple method, we will define aSmall 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. Scenario
- 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
DogClass, and then give this Class a
bitemethod.
class Dog { bite(Human) { // ...... } }复制代码
bitehappens 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.
biteBybehavior 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?
hurtto 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) { //...... } }复制代码
狗咬人在实际开发场景中,是一个业务逻辑,我们只需要设计改变人Human
对象内部的状态的行为,所以它正确的命名应该是hurt
。这里的damage
,可以从狗 Class 中咬bite
, 的行为方法中计算或者生成出来的一个对象,但是如果我们直接传狗Dog
的对象进来的话,肯定是不符合我们对对象的抽象原则的。
最终我们的代码实现逻辑如下:
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复制代码
设计对象的原则:
- 我们不应该受到语言描述的干扰(特别是业务需求的干扰)
- 在设计对象的状态和行为时,我们总是遵循 “行为改变状态” 的原则
- 违背了这个原则,整个对象的内聚性就没有了,这个对架构上会造成巨大的破坏
相关免费学习推荐:javascript(视频)
The above is the detailed content of Relearning JavaScript objects. For more information, please follow other related articles on the PHP Chinese website!