Object Oriented Javascript OOP

  • 2021-07-06 09:57:34
  • OfStack

Object-oriented programming (Object-oriented, programming, OOP) is not only a paradigm of programming, but also a method of programming. An object refers to an instance of a class. It takes object as the basic unit of program and encapsulates program and data in it to improve the reusability, flexibility and extensibility of software. -Wikipedia

1 general object-oriented includes: inheritance, encapsulation, polymorphism, abstraction

Inheritance in the form of objects

Shallow copy


var Person = {
  name: 'allin',
  age: 18,
  address: {
    home: 'home',
    office: 'office',
  }
  sclools: ['x','z'],
};

var programer = {
  language: 'js',
};

function extend(p, c){
  var c = c || {};
  for( var prop in p){
    c[prop] = p[prop];
  }
}
extend(Person, programer);
programer.name; // allin
programer.address.home; // home
programer.address.home = 'house'; //house
Person.address.home; // house

From the above results, it can be seen that the defect of shallow copy is that it modifies the value of reference type in child object, which will affect the value in parent object, because the copy of reference type in shallow copy only copies the address and points to the same copy in memory.

Deep copy


function extendDeeply(p, c){
  var c = c || {};
  for (var prop in p){
    if(typeof p[prop] === "object"){
      c[prop] = (p[prop].constructor === Array)?[]:{};
      extendDeeply(p[prop], c[prop]);
    }else{
      c[prop] = p[prop];
    }
  }
}

Use recursion for deep copying, so that the modification of the object will not affect the parent object.


extendDeeply(Person, programer);
programer.address.home = 'allin';
Person.address.home; // home
 Utilization call And apply Inheritance 
function Parent(){
  this.name = "abc";
  this.address = {home: "home"};
}
function Child(){
  Parent.call(this);
  this.language = "js"; 
}
ES5 In Object.create()
var p = { name : 'allin'};
var obj = Object.create(o);
obj.name; // allin

Object. create () as an alternative to the new operator came out after ES5. We can also simulate this method ourselves:


// Simulation Object.create() Method 
function myCreate(o){
  function F(){};
  F.prototype = o;
  o = new F();
  return o;
}
var p = { name : 'allin'};
var obj = myCreate(o);
obj.name; // allin

At present, the latest versions of major browsers (including IE9) have deployed this method. If you encounter an old browser, you can deploy it yourself with the following code.


    if (!Object.create) {
          Object.create = function (o) {
                 function F() {}
                F.prototype = o;
                return new F();
          };
    }

Inheritance of classes


Object.create()
function Person(name, age){}
Person.prototype.headCount = 1;
Person.prototype.eat = function(){
  console.log('eating...');
}
function Programmer(name, age, title){}

Programmer.prototype = Object.create(Person.prototype); // Establish inheritance relationship 
Programmer.prototype.constructor = Programmer; //  Modify constructor Direction of 

Call the parent class method


function Person(name, age){
  this.name = name;
  this.age = age;
}
Person.prototype.headCount = 1;
Person.prototype.eat = function(){
  console.log('eating...');
}

function Programmer(name, age, title){
  Person.apply(this, arguments); //  Call the constructor of the parent class 
}


Programmer.prototype = Object.create(Person.prototype);
Programmer.prototype.constructor = Programmer;

Programmer.prototype.language = "js";
Programmer.prototype.work = function(){
  console.log('i am working code in '+ this.language);
  Person.prototype.eat.apply(this, arguments); //  Calling a method on the parent class 
}

Encapsulation

Namespace

js has no namespace, so it can be impersonated with objects.


var app = {}; //  Namespace app
// Module 1
app.module1 = {
  name: 'allin',
  f: function(){
    console.log('hi robot');
  }
};
app.module1.name; // "allin"
app.module1.f(); // hi robot

Static member


function Person(name){
  var age = 100;
  this.name = name;
}
// Static member 
Person.walk = function(){
  console.log('static');
};
Person.walk(); // static

Private and public ownership


function Person(id){
  //  Private properties and methods 
  var name = 'allin';
  var work = function(){
    console.log(this.id);
  };
  // Public attributes and methods 
  this.id = id;
  this.say = function(){
    console.log('say hello');
    work.call(this);
  };
};
var p1 = new Person(123);
p1.name; // undefined
p1.id; // 123
p1.say(); // say hello 123

Modularization


function extendDeeply(p, c){
  var c = c || {};
  for (var prop in p){
    if(typeof p[prop] === "object"){
      c[prop] = (p[prop].constructor === Array)?[]:{};
      extendDeeply(p[prop], c[prop]);
    }else{
      c[prop] = p[prop];
    }
  }
}
0

prop, func will not be leaked to the global scope. Or another way of writing, use new


function extendDeeply(p, c){
  var c = c || {};
  for (var prop in p){
    if(typeof p[prop] === "object"){
      c[prop] = (p[prop].constructor === Array)?[]:{};
      extendDeeply(p[prop], c[prop]);
    }else{
      c[prop] = p[prop];
    }
  }
}
1

Polymorphism

Simulation method overload

The arguments attribute can get the number of arguments for the function call, and this 1 point can be used to simulate the overload of the method.


function extendDeeply(p, c){
  var c = c || {};
  for (var prop in p){
    if(typeof p[prop] === "object"){
      c[prop] = (p[prop].constructor === Array)?[]:{};
      extendDeeply(p[prop], c[prop]);
    }else{
      c[prop] = p[prop];
    }
  }
}
2

Method override


function F(){}
var f = new F();
F.prototype.run = function(){
  console.log('F');
}
f.run(); // F

f.run = function(){
  console.log('fff');
}
f.run(); // fff

Abstract class

In the constructor throw new Error (''); Throw an exception. This prevents the class from being called directly.


function extendDeeply(p, c){
  var c = c || {};
  for (var prop in p){
    if(typeof p[prop] === "object"){
      c[prop] = (p[prop].constructor === Array)?[]:{};
      extendDeeply(p[prop], c[prop]);
    }else{
      c[prop] = p[prop];
    }
  }
}
4


Related articles: