Home Web Front-end JS Tutorial What is polymorphism in Javascript language

What is polymorphism in Javascript language

Jan 29, 2018 pm 01:45 PM
javascript js language

The Java language is a statically typed language. Due to strict type checking when compiling the code, variables cannot be assigned values ​​of different types. This type checking will make the code rigid, but Java also The effect of polymorphism can be obtained through inheritance (implementation inheritance and interface inheritance). Polymorphism can be achieved by upward transformation.

The actual meaning of polymorphism is that the same operation, acting on different objects, can produce different interpretations and different execution results. The variable type of JavaScript is variable at runtime, which means that the polymorphism of JavaScript objects is inherent.

The following picture explains it:

The master gives instructions to "chicken and duck" at the same time. The chicken and duck croak at the same time, but their The cry is different.
What is polymorphism in Javascript language

We use code to demonstrate this example:

In traditional code, we are used to using if else to stack hard-coded code, but if this object Keeping it up will result in continuous addition of code. It is always dangerous to modify the code. The more places you modify, the greater the possibility of program errors. And when there are more types of animals, it will cause if else It is piled up into a huge function, which is not conducive to maintenance.

var makeSound = function(animal) {
     if (animal instanceof Dog) {
        console.log('wanwan');
     } else if(animal instanceof Cat) {
        console.log('miaomiao');
     }
}

var Dog = function() {}
var Cat = function() {}
makeSound(new Dog());
makeSound(new Cat());
Copy after login

The modified code is as follows:

 var makeSound = function(animal) {
     animal.sound();
}
var Dog = function() {}
Dog.prototype.sound = function(){
   console.log('wanwan');
}

var Cat = function() {}
Cat.prototype.sound = function() {
   console.log('miaomiao');
}
makeSound(new Dog());
makeSound(new Cat());
Copy after login

How to understand that if the object cannot respond to a request, it will delegate the request to the prototype of its constructor. This principle is prototypal inheritance The essence of , here is a piece of code:

var obj = {name:'lin'};

var A = function() {};

A .prototype = obj;

var a = new A();
console.log(a.name);

Explanation: Traversing all the attributes of object a, name was not found Properties
The request to find the name property is delegated to the prototype of object a's constructor, which is recorded by a._proto_ and points to A.prototype,
and A.prototype is set to object obj
in Find the name attribute in object obj and return it.

Related recommendations:

How to learn JavaScript language? What are the important and difficult points in learning?

JavaScript language structure notes (1)_Basic knowledge

Detailed explanation of the basic grammatical requirements of JavaScript language_Basic knowledge


The above is the detailed content of What is polymorphism in Javascript language. 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)

3 Ways to Change Language on iPhone 3 Ways to Change Language on iPhone Feb 02, 2024 pm 04:12 PM

It's no secret that the iPhone is one of the most user-friendly electronic gadgets, and one of the reasons why is that it can be easily personalized to your liking. In Personalization, you can change the language to a different language than the one you selected when setting up your iPhone. If you're familiar with multiple languages, or your iPhone's language setting is wrong, you can change it as we explain below. How to Change the Language of iPhone [3 Methods] iOS allows users to freely switch the preferred language on iPhone to adapt to different needs. You can change the language of interaction with Siri to facilitate communication with the voice assistant. At the same time, when using the local keyboard, you can easily switch between multiple languages ​​to improve input efficiency.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to set the language of Win10 computer to Chinese? How to set the language of Win10 computer to Chinese? Jan 05, 2024 pm 06:51 PM

Sometimes we just install the computer system and find that the system is in English. In this case, we need to change the computer language to Chinese. So how to change the computer language to Chinese in the win10 system? Now Give you specific operation methods. How to change the computer language in win10 to Chinese 1. Turn on the computer and click the start button in the lower left corner. 2. Click the settings option on the left. 3. Select "Time and Language" on the page that opens. 4. After opening, click "Language" on the left. 5. Here you can set the computer language you want.

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

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

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Exploring the boundaries of agents: AgentQuest, a modular benchmark framework for comprehensively measuring and improving the performance of large language model agents Exploring the boundaries of agents: AgentQuest, a modular benchmark framework for comprehensively measuring and improving the performance of large language model agents Apr 11, 2024 pm 08:52 PM

Based on the continuous optimization of large models, LLM agents - these powerful algorithmic entities have shown the potential to solve complex multi-step reasoning tasks. From natural language processing to deep learning, LLM agents are gradually becoming the focus of research and industry. They can not only understand and generate human language, but also formulate strategies, perform tasks in diverse environments, and even use API calls and coding to Build solutions. In this context, the introduction of the AgentQuest framework is a milestone. It not only provides a modular benchmarking platform for the evaluation and advancement of LLM agents, but also provides researchers with a Powerful tools to track and improve the performance of these agents at a more granular level

How to change the language display of vivox60pro vivox60pro system language setting method How to change the language display of vivox60pro vivox60pro system language setting method Mar 23, 2024 am 09:06 AM

1. Click [System Management] in the phone settings menu. 2. Click the [Language] option. 3. Select the system language you want to use.

See all articles