search
HomeWeb Front-endJS TutorialLearn more about Objects in JavaScript

Learn more about Objects in JavaScript

Jul 07, 2021 am 10:57 AM
javascriptobjectobject

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) {
    // ......
  }
}

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) {
    //......
  }
}

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

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
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools