Home >Web Front-end >JS Tutorial >An in-depth analysis of JavaScript design patterns: polymorphism
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('age: 26');<br/>};<br/><br/>var Olive = function() {};<br/>Olive.prototype.age = function() {<br/> console.log('age: 20');<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:
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!