Home>

JavaScript is an object-based language, and almost everything you encounter is an object.However, it is not a true object-oriented programming (oop) language, because it does not have a class in its syntax.

Object-oriented programming (oop) is a programming paradigm.It is also a method of program development.An object refers to an instance of a class.It uses objects as the basic unit of a program,Encapsulating programs and data,To improve software reusability, flexibility, and scalability.--Wikipedia

General object-oriented includes:inheritance, encapsulation, polymorphism, abstraction

Object form inheritance

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 results above,The disadvantage of shallow copy is that the value of the reference type in the child object is modified.Affects the values ​​in the parent object,Because the copy of the reference type in shallow copy only copies the address,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];
    }
  }
}

Deep copy using recursion,In this way, modification of the child object will not affect the parent object.

extenddeeply (person, programer);
programer.address.home="allin";
person.address.home;//home
Use call and apply inheritance
function parent () {
  this.name="abc";
  this.address={home:"home"};
}
function child () {
  parent.call (this);
  this.language="js";
}
object.create () in es5
var p={name:"allin"};
var obj=object.create (o);
obj.name;//allin

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

//Simulate 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

Currently, 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 ();
};
}

Class inheritance

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
programmer.prototype.constructor=programmer;//modify the pointer of the constructor

Call parent 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);//call a method on the parent class
}

Encapsulation

Namespaces

js has no namespace,So you can use object simulation.

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

function person (id) {
  //Private properties and methods
  var name="allin";
  var work=function () {
    console.log (this.id);
  };
  //Public properties 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

Modular

var modulea;
modulea=function () {
  var prop=1;
  function func () {}
  return {
    func:func,    prop:prop
  };
) ();//execute anonymous function immediately

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

modulea=new function () {
  var prop=1;
  function func () {}
  this.func=func;
  this.prop=prop;
}

Polymorphism

Simulation method overload

The arguments property can get the number of actual parameters of the function call.You can use this to simulate overloading of methods.

function demo (a, b) {
  console.log (demo.length);//get the number of formal parameters
  console.log (arguments.length);//Get the number of arguments
  console.log (arguments [0]);//first argument 4
  console.log (arguments [1]);//second argument 5
}
demo (4, 5, 6);
//Implement the addition of variable-length arguments
function add () {
  var total=0;
  for (var i=arguments.length-1;i>= 0;i-) {
    total +=arguments [i];
  }
  return total;
}
console.log (add (1));//1
console.log (add (1, 2, 3));//7
//In case of different parameters
function fontsize () {
  var ele=document.getelementbyid ("js");
  if (arguments.length == 0) {
    return ele.style.fontsize;
  } else {
    ele.style.fontsize=arguments [0];
  }
}
fontsize (18);
console.log (fontsize ());
//different types
function setting () {
  var ele=document.getelementbyid ("js");
  if (typeof arguments [0] === "object") {
    for (var p in arguments [0]) {
      ele.style [p]=arguments [0] [p];
    }
  } else {
    ele.style.fontsize=arguments [0];
    ele.style.backgroundcolor=arguments [1];
  }
}
setting (18, "red");
setting ({fontsize:20, backgroundcolor:"green"});

Method rewrite

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

Throw new error ("");in the constructor. This prevents this class from being called directly.

function detectorbase () {
  throw new error ("abstract class can not be invoked directly!");
}
detectorbase.prototype.detect=function () {
  console.log ("detection starting ...");
};
detectorbase.prototype.stop=function () {
  console.log ("detection stopped.");
};
detectorbase.prototype.init=function () {
  throw new error ("error");
};
//var d=new detectorbase ();//uncaught error:abstract class can not be invoked directly!
function linkdetector () {}
linkdetector.prototype=object.create (detectorbase.prototype);
linkdetector.prototype.constructor=linkdetector;
var l=new linkdetector ();
console.log (l);//linkdetector () __ proto__:linkdetector
l.detect ();//detection starting ...
l.init ();//uncaught error:error
  • Previous Summary of JavaScript string methods
  • Next C # basic knowledge of FileStream