The object-oriented basics of Javascript OOP

Source: Internet
Author: User
Tags extend inheritance shallow copy

Object-Oriented programming (Object-oriented Programming,oop) is a programming paradigm and a method of program development. Object refers to an instance of a class. It encapsulates the program and data as the basic unit of the program to improve the reusability, flexibility and scalability of the software. --Wikipedia

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

Inheritance of Object forms

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 flaw in a shallow copy is that modifying the value of a reference type in a child object affects the values in the parent object because copies of reference types in a shallow copy simply copy the address and point 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];
    }
  }

By using recursion for deep copying, the modification of the object does not affect the parent object.

Extenddeeply (person, programer);
Programer.address.home = ' Allin ';
Person.address.home; Home
uses call and apply to
inherit function Parent () {
  this.name = "abc";
  This.address = {home: ' home '};
}
function Child () {
  parent.call (this);
  This.language = "JS"; 
}
Object.create ()
var p = {name: ' Allin '} in ES5;
var obj = object.create (o);
Obj.name; Allin

Object.create () as an alternative to the new operator is ES5. 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

This method is currently deployed in the latest versions of the major browsers, including IE9. If you encounter an older 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; To modify the constructor point

Calling 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 constructor of 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 methods on the parent class
}

Packaging

Name space

JS is not a namespace, so you can simulate it 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 members

function person (name) {
  var age = m;
  this.name = name;
static member
Person.walk = function () {
  console.log (' static ');
Person.walk (); Static

Private and public

function person (ID) {
  //private property and Method
  var name = ' Allin ';
  var work = function () {
    console.log (this.id);
  };
  Public property and method
  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

of modular

var Modulea;
Modulea = function () {
  var prop = 1;

  function func () {} return

  {
    func:func,
    prop:prop
  };
} (); Execute anonymous function now

Prop,func will not be compromised to the global scope. Or another way of writing, using new

Modulea = new function () {
  var prop = 1;

  function func () {}

  This.func = func;
  This.prop = prop;
}

Polymorphic

Impersonation method overload

The arguments property can take the number of arguments of a function call, which can be used to simulate the overload of a method.

function Demo (A, b) {console.log (demo.length);//Get the number of parameters Console.log (arguments.length);//Get the number of arguments Console.log (argum Ents[0]); The first argument 4 Console.log (arguments[1]);
Second Argument 5} demo (4, 5, 6);
  The Add function Add () {var total = 0 For variable length arguments is implemented.
  for (var i = arguments.length-1 i >= 0; i--) {total = Arguments[i];
Return to total; } console.log (Add (1)); 1 Console.log (Add (1, 2, 3));
  7//Parameter different situation 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 of situations 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 (, ' Red '); Setting ({fontsize:20, backgroundcolor: ' Green '});

 

Method overrides

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 the new Error (') in the constructor; Throw the exception. This prevents this class from being invoked 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 is 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.