Home  >  Article  >  Web Front-end  >  An in-depth analysis of JavaScript design patterns: polymorphism

An in-depth analysis of JavaScript design patterns: polymorphism

零到壹度
零到壹度Original
2018-04-04 14:59:401245browse

This article mainly introduces an in-depth analysis of JavaScript design patterns: polymorphism. The editor thinks it is quite good. I will share it with you now and give it as a reference. Let’s follow the editor to take a look.

The meaning of polymorphism

The same operation can produce different interpretations when applied to different objects. and different execution structures. That is, when the same message is sent to different objects, these objects will give different feedback based on the message.



The idea behind polymorphism

will "do "What" is separated from "who does it and how", that is, "unchangeable things" are separated from "changeable things".


Polymorphism of objects

<span style="font-family: 微软雅黑, "Microsoft YaHei";">// 要做的事情:输出用户的年龄<br/>var printAge = function(person) {<br/>  if (person.age instanceof Function) {<br/>    person.age();<br/>  }<br/>};<br/><br/>// 都有哪些用户以及这些用户要怎么做一些事情<br/>var Jack = function() {};<br/>Jack.prototype.age = function() {<br/>  console.log(&#39;age: 26&#39;);<br/>};<br/><br/>var Olive = function() {};<br/>Olive.prototype.age = function() {<br/>  console.log(&#39;age: 20&#39;);<br/>};<br/><br/>printAge( new Jack() );  // age: 26<br/>printAge( new Olive() );  // age: 20<br/></span>


Advantages of object-oriented design
Distribute behavior among various objects and let each of these objects be responsible for their own behavior. This is the advantage of object-oriented design.


related suggestion:

js implements polymorphism

Inheritance and polymorphism in JavaScript

A brief discussion on JavaScript polymorphism and encapsulation

The above is the detailed content of An in-depth analysis of JavaScript design patterns: polymorphism. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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