Encapsulation, inheritance and polymorphism of js objects

Keywords: Javascript Attribute

The three main characteristics of object-oriented are encapsulation inheritance and polymorphism. Simply understand, for cat, it is a encapsulated class itself. You only need to feed and drink (input), it can show cat's behavior (output), and it inherits animal's habits (eating, etc.). Different cats because Different environments or habits may have different manifestations and behaviors, which is polymorphism.

encapsulation
It encapsulates objective things into abstract classes, hides the implementation details of attributes and methods, and only exposes interfaces to the outside world.

Before ES6, there was no concept of class, which was realized by prototype objects and constructors.

function Cat(name, food) {
  this.name = name // Public property
  this.food = food
}
Cat.prototype.say = function() { // public Method
  console.log(this.name + " likes eating " + this.food)
}
Cat.see = function() {
  console.log('This is a static method without instantiating callable')
}
var cat = new Cat("Lazier","mouse")
cat.say() // Example Sharing Prototype Attributes and Methods

class of ES6

class Cat{
  constructor(name, food){
    this.name = name
    this.food = food
  }
  static see() {
    console.log('This is a static method without instantiating callable')
  }
  say(){
    console.log(this.name+" likes eating " + this.food)
  }
}
var cat = new Cat("Lazier","mouse")
cat.say()

The basic principles of the above class es are as follows_

var Cat = function(){
  function Cat(name, food){
    this.name = name
    this.food = food
  }
  // Execute mount functions to create classes
  createClass(Cat,[{key:"say",value:function(){
    console.log(this.name+" likes eating " + this.food)
  }}],[{key:"see",value:function(){
    console.log('This is a static method without instantiating callable')}])
}

// Define object attributes
let defineProperties = function(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i]
    Object.defineProperty(target, descriptor.key, descriptor)
  }
}   
// Mount functions that mount static or dynamic methods on Cat and Cat prototype s, respectively
var createClass = function({
  return function(Constructor,protoProps,staticProps){
    if(protoProps){ // Prototype method
      defineProperties(Constructor.prototype,protoProps)
    }
    if(staticProps){ // Static method
      defineProperties(Constructor,staticProps)
    }
  }
})

Understanding object-oriented public, private, static attributes and methods can be summarized in the following article

js object-oriented public, private, static attributes and methods

inherit
Subclasses can use all the functions of the parent class and extend these functions. The process of inheritance is from general to special.

There are many ways to implement inheritance in js

Prototype chain inheritance

// Point the prototype of the child class to the instance of the parent class
function Parent(){}
function Son(){}
Son.prototype = new Parent()
// * Pointing the constructor of Son's prototype object to Son to solve the problem of type judgment
Son.prototype.constructor = Son
//Inheritance by Constructor (Inheritance by call and apply)
function Parent(){}
function Son(){
    // Force binding this in a parent function to this in a child class
    // Transferable reference
    Parent.call(this, arguments);
}
//Combinatorial Inheritance
// Prototype attribute method is inherited by prototype chain, and instance attribute method is inherited by borrowing constructor.
// In this way, function reuse is realized by defining method on prototype, and each instance has its own attributes.
function Parent(name){
    this.name = name
}
function Son(name, age){
    // Inherit the instance attribute method of the parent class, and then add your own instance attribute method
    Parent.call(this, name);
    this.age = age
}
Son.prototype = new Parent()
// Rewrite Son's prototype object
Son.prototype.constructor = Son

var demo = new Son("jacksonzhou", 23)
//Parasitic combinatorial inheritance - the most commonly used inheritance method nowadays
// Get a copy of the parent prototype attribute method to solve the problem of attribute duplication in combination inheritance
function inheritPrototype(son, parent) {
    var prototype = object(parent.prototype)
    prototype.constructor = son
    son.prototype = prototype
}

function Parent(name){
    this.name = name
}
function Son(name, age){
    Parent.call(this, name)
    this.age = age
}
Son.prototype = inheritPrototype(Son, Parent)

var demo = new Son("jacksonzhou", 23)

polymorphic
When the same operation is used on different objects, different interpretations and different execution results can be produced.

var makeSound=function(animal){
  animal.sound()
}
// Declare the dog's constructor
var Dog=function(){}
Dog.prototype.sound=function(){
  console.log('Wang Wang Wang')
}
// Declare the cat's constructor
var Cat=function(){}
Cat.prototype.sound=function(){
  console.log('cat')
}
// Call their names separately
makeSound(new Dog())
makeSound(new Cat())
// Nonpolymorphic Writing
var makeSound=function(animal){
  if(animal instanceof Dog){
    console.log('Wang Wang Wang')
  }else if(animal instanceof Cat){
    console.log('cat')
  }
}
var Dog=function(){}
var Cat=function(){}
// Call their names separately
makeSound(new Dog())
makeSound(new Cat())
// Obviously, it's not elegant to modify the makeSound function when other animals join in the future.
//Here's how to overload

//Method overloading is a means for classes to process different types of data in a unified way. It shows that there are many functions with the same name, but they have different parameters or types. It is also a polymorphism that methods are called by determining which method to use by the number and type of parameters passed to them.

//In fact, js itself does not have this concept, but we can simulate the effect of overloading function by selecting different implementations according to the length of the class array arguments of operation parameters and the type of its elements.

// js's function parameters are quite flexible ~can be understood as a dynamic array of classes
// Without parameters, there will be no errors when incoming parameters are invoked.
function countCat(){ 
  if(arguments.length==1){ 
    console.log(`This is a cat.,${arguments[0]}`)
  } 
  else if(arguments.length==2){ 
    console.log(`These are two cats.,${arguments[0]}and ${arguments[1]}`)
  } 
  else{
    console.log("No cats~")
  } 
} 
countCat()
countCat("Tom")
countCat("Tom","Mary")

Posted by azukah on Thu, 22 Aug 2019 01:30:58 -0700