Definition of Class
Way One
varBook =function(ID, name, price) {//private property, external cannot be accessed directly varnum = 1; //Private Methods, functionCheckid () {}; This. GetName =function(){}; This. GetPrice =function(){}; This. SetName =function(){}; This. Setprice =function(){}; This. ID =ID; This. Copy =function(){}; This. SetName (name); This. Setprice (price);} Book.ischinese=true; Book.resettime=function() {Console.log (' New Time ');} Book.prototype={isjsbook:false, display:function(){} }varb =NewBook (one, ' JavaScript design mode ', 50); Console.log (B.num); Console.log (B.isjsbook); Console.log (b.id); Console.log (B.ischinese) ;
Way Two
varBook = (function(){ varBooknum = 0; functionCheckbook (name) {}//returns the constructor function return function(newid,newname,newprice) {//Private Variables varName,price; //Private Methods functionCheckid (ID) {}//Privileged Methods This. GetName =function(){}; This. GetPrice =function(){}; This. SetName =function(){}; This. Setprice =function(){}; //Common Attributes This. ID =newId; //Public Methods This. Copy =function(){}; Booknum++; if(booknum>100){ Throw NewError (' We only publish 100 books '); } This. SetName (name); This. Setprice (price); }})(); Book.prototype= { //static public PropertiesIsjsbook:false, display:function(){}}
Mode three
varBook = (function() { //static private variable 0 varBooknum = 0; //Static Private Methods functionCheckbook (name) {}//Create Class function_book (newid,newname,newprice) {//Private Variables varName,price; Name=NewName; Price=Newprice; //Private Methods functionCheckid (ID) {}//Privileged methods (objects created can be accessed) This. GetName =function(){returnname;}; This. GetPrice =function(){returnPrice ;}; This. SetName =function(Mingcheng) {name =Mingcheng;}; This. Setprice =function(){}; //Public properties (objects can be accessed) This. ID =newId; //Public methods (objects can be accessed) This. Copy =function(){}; Booknum++; if(booknum>100){ Throw NewError (' We only publish 100 books '); } //Constructors This. SetName (name); This. Setprice (price); } //Constructing prototypes_book.prototype = { //static public PropertiesIsjsbook:false, //static public methodsDisplayfunction(){return' Hello World '} }; return_book;}) ();varBook =NewBook (' JavaScript ', 100); Console.log (book); Console.log (Book.isjsbook); Console.log (Book.getname ()); Console.log (book.id); Console.log (Book.getprice ()); Book.setname (' Test01 '); Console.log (Book.getname ()); Console.log (Book.display ()) ;
Test environment node. JS version 8.10.0
Please leave a message if you have any copyright issues, or add me qq362601125
Reference list
1. The author of JavaScript design mode Zhang Rongming
JavaScript Object-oriented Programming (ii) Encapsulation of classes