A preface.

We know that object orientation is characterized by encapsulation, inheritance, and polymorphism.

  1. Encapsulation: hides the properties and implementation details of a class (such as private and protect properties), provides a public interface for reading and modifying properties (such as the set constructor and get constructor functions in c++, Java, etc.), and exposes only those properties and methods that need to be exposed.

  2. Inheritance: Subclasses own and extend the behavior and properties of the base class. For example: the inheritance of human biology.

  3. Polymorphic: Responses between different objects in the same method, i.e. the same operation on different objects, can result in different interpretations and different execution results. For example: we right click to open any file, call open method, MP4 is called after the video player to play the video, MP3 is the music player to play the changed music, pictures open is the picture preview program. That’s polymorphism.

In the first two articles, we have covered almost all the features of encapsulation and inheritance. This chapter will cover the implementation of polymorphism in the JavaScript language.

2. Basic ideas

The main idea is to call a function whose parameter is a reference to a superclass.

Tips: Since JS is a weak language type; Parameter, and then call the corresponding method

Let’s start with the following implementation of Java code polymorphism:

    package juejinBlog;

// Superclass: file
abstract class File {
	protected String name;
	// constructor
	File(String name) {
		this.name = name;
	}
	public abstract void open(a);
	
	public String getName(a) {
		return name;
	}
	public void setName(String name) {
		this.name = name; }};// Subclass: video file
class Video extends File {
	// constructor
	Video(String name) {
		super(name);
	}

	@Override
	public void open(a) {
		System.out.println("Opened video file :"+this.name); }}// Subclass: image file
class Image extends File {
	Image(String name) {
		super(name);
	}
	@Override
	public void open(a) {
		System.out.println("Opened image file :"+this.name); }}/ / test class
public class Polymorphism {
	// The core method is used to weaken the type and replace N implementations with an abstract object.
	public static void openFile(File file) {
		file.open();
	} 
        / / the main function
	public static void main(String[] args) {
		Video mp4 = new Video("Corporate Promotional Video. Mp4");
		Image img = new Image("Picture 1. The PNG"); System.out.println(mp4.getName()); System.out.println(img.getName()); openFile(mp4); openFile(img); }}Copy the code

The running results are as follows:

Analysis: If we look at the core method openFile, we can observe that the parameter is a reference to a top-level class, and the function body calls the open method directly. When we call openFile and pass in different subclass instances we find that the open method of the corresponding class is automatically called; Java’s polymorphic implementation is very simple.

Tips: Java does the casting automatically, without our judgment.

Polymorphic implementation in JavaScript.

Let’s simulate the implementation of the core method in Java to see if we can accomplish polymorphism. Let’s look at the following code.

Superclasses: file classes

    // file.js
    class File {
  __name = "";
  constructor(name) {
    if (new.target === File) {
      throw new Error("Abstract classes cannot be instantiated");
    }
    this.__name = name;
  }

  setFileName(name) {
    this.__name = name;
  }

  getFileName() {
    return this.__name;
  }

  open(){}}export default File;
Copy the code

Subclass: Video class

  // video.js
  import File from "./file";

class Video extends File {
  constructor(name) {
    super(name);
  }
  open() {
    console.log('Opened the video fileThe ${this.__name}`); }}export default Video;

Copy the code

Subclass: Picture class

//image.js
import File from "./file";

class Image extends File {
  constructor(name) {
    super(name);
  }
  open() {
    console.log('Opened the pictureThe ${this.__name}`); }}export default Image;
Copy the code

Test file: index.js

import Image from "./mutipleSector/image";
import Video from "./mutipleSector/video";
// Core method
function openFile(file) {
  file.open();
}

let mp4 = new Video("My Video. Mp4");
let image = new Image("My image.png");
console.log(mp4.getFileName());
console.log(image.getFileName());

openFile(mp4);
openFile(image);
Copy the code

Running results:

No matter how many subclasses you have, just call openFile(

Four conclusions.

Polymorphism is the result of strong typing, and for strongly typed languages such as C++, C#, and Java, a higher level of abstraction (the File class used in this case) is usually taken by abstract classes or interfaces.

This is essentially to “weaken concrete types” (replace N concrete implementations with an “abstract”, as in the Java example of the openFile method).

In the Java example we add two lines to the main function:

    // Weaken the specific type
    File f1 = new Video("Test video file.avi");
    File f2 = new Image("Test image file.png");
    f1.open();
    f2.open();
Copy the code

The running results are shown as follows:

We found that js in fact polymorphic implementation is very easy, that is, function pass parameters. The reason for this is the nature of the JS language: it is inherently weakly typed.

  1. Polymorphism is the result of strong typing.

  2. For the JS language, which is itself a weak type, polymorphism is inherent.