Object-oriented programming (OOP) is a programming paradigm and also a method of program development. An object refers to an instance of a class. It uses objects as the basic unit of the program, encapsulating programs and data in it to improve the reusability, flexibility and scalability of the software. -- Wikipedia
Generally, object-oriented includes: inheritance, encapsulation, polymorphism, abstraction
Inheritance of object form
Light 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, program);programer.name; // allinprogramer.address.home; // homeprogramer.address.home = 'house'; //housePerson.address.home; // houseFrom the above results, the flaw of shallow copy is that modifying the value of the reference type in the child object will affect the value in the parent object, because in the shallow copy of the reference type 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 sub-objects will 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() in ES5 var p = { name : 'allin'};var obj = Object.create(o);obj.name; // allinObject.create() as an alternative to new operator is only released after ES5. We can also simulate this method ourselves:
//Simulate the 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; // allinCurrently, the latest versions of major browsers (including IE9) have deployed this method. If you encounter an old browser, you can use the following code to deploy it yourself.
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); //Create an inheritance relationship Programmer.prototype.constructor = Programmer; //Modify the constructor's pointingCall 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); // Call the method on the parent class}Package
Namespace
js has no namespace, so it can be simulated with objects.
var app = {}; // Namespace app//Module 1app.module1 = { name: 'allin', f: function(){ console.log('hi robot'); }};app.module1.name; // "allin"app.module1.f(); // hi robotStatic members
function Person(name){ var age = 100; this.name = name;}//static member Person.walk = function(){ console.log('static');};Person.walk(); // staticPrivate 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; // undefinedp1.id; // 123p1.say(); // say hello 123Modular
var moduleA;moduleA = function() { var prop = 1; function func() {} return { func: func, prop: prop };}(); // Execute anonymous function immediatelyprop, 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;}Polymorphic
Simulation method reload
The arguments attribute can obtain the number of actual parameters of a function call, and can use this to simulate the overloading of the method.
function demo(a, b ){ console.log(demo.length); // Get the number of formal parameters console.log(arguments.length); // Get the number of actual parameters console.log(arguments[0]); // The first actual parameter 4 console.log(arguments[1]); // The second actual parameter 5}demo(4, 5, 6); // Implement the addition of variable length actual parameters function add(){ var total = 0; for( var i = arguments.length - 1; i >= 0; i--){ total += arguments[i]; } return total;}console.log(add(1)); // Implement the addition of variable length actual parameters function add(){ var total = 0; for( var i = arguments.length - 1; i >= 0; i--){ total += arguments[i]; } return total;}console.log(add(1)); // 1console.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());// In case of 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(); // Ff.run = function(){ console.log('fff');}f.run(); // fffAbstract Class
throw new Error(''); in the constructor throws exception. 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__: LinkDetectorl.detect(); //Detection starting...l.init(); //Uncaught Error: Error