This article applies to ES6 before ...
JavaScript needs to use functions to emulate classes.
function Book (name) { this. Name = name; This function () { returnthis. Name; } This function (nname) { this. Name= nname; }}
New An Object
var New Book ("C #"); // The new operation here is equivalent to creating a simple object, calling the constructor of the class
Each function has a prototype object on top of it--prototype
var proto = book.prototype; = "string"; function () { alert ("Hello"); } // after defining properties and methods for the prototype, the class that owns the function of the prototype object is also given the property and method // Eject string // pop- up Hello}
Add a common question
functionAnimal (name) { This. Name =name; This. Age = 0; } varA1 =Animal; alert (A1); //eject the entire function body varA2 = Animal ("Dinglang"); alert (A2); //Eject undefined varA3 =Newanimal (); Alert (A3);//Eject Object vara4 =NewAnimal; alert (A4);//Eject Object
Class modification, extension (emphasis, difficulty)
//1. If I want to implement a simple addition calculation var numone = 5;//If defined directly, then the following numone.add (8); execution will error //If I write this, the following call will not be an error (because at this time the Numone, is a class. Equivalent to the original basic data type, wrapper type in the Java or C # language) varNumone =NewNumber (5); Numone.add=function(numtwo) {return This+Numtwo; } alert (numone.add);//undefined Alert (Numone.add (8));//It seems correct to write, but it will error--numone.add is not a function varNumthree =NewNumber (100); //If I want to add a function to the Numthree object now. //It is implemented directly using the special property of prototype, adding the Add function to all instances of number typeNumber.prototype.add =function(numtwo) {return This+Numtwo; } alert (Numthree.add (Add (300));//pop-up 100+200+300=600
Implementing Inheritance in JavaScript
functionClassA (name) { This. Name =name; This. ShowName =function() {alert ( This. Name); } } functionClassB (name) {//1) Implement inheritance using the Newmethod method //This.newmethod = ClassA; //This.newmethod (name); //delete This.newmethod;//Release Object //2) Call the Claasa function and point his context (scope) to this (that is, an instance of the ClassB Class) //This also allows for inheritance (using call or Apply)Classa.call ( This, name); //classa.apply (This,[name]); } obja=NewClassA ("Operating system"); OBJB=NewClassB ("Composition principle"); Obja.showname (); //Eject "operating system"Objb.showname ();//Eject "Composition principle" })
OOP Programming in JS