prototype (prototype): All JS objects can be extended by their prototypes, and this feature allows the creation of custom classes.
/*var answer = 0;//code is too strong, not local scope means it can be modified in any part of the program function AddNumbers (NUM1, num2) {answer = NUM1 + num2; }//Each function is orphaned in the global scope, contaminating the global scope function subtractnumbers (NUM1, num2) {answer = num1-num2; } function Multiplynumbers (NUM1, num2) {answer = NUM1 * NUM2; } function Dividenumbers (NUM1, num2) {if (num2! = 0) {answer = num1/num2; } else {answer = 0; }} addnumbers (1, 2); alert (answer); Subtractnumbers (1, 2); alert (answer); Multiplynumbers (1, 2); alert (answer); Dividenumbers (1, 2); alert (answer); */ functionNumberfunctions () {//object-oriented, good structure, easy to understand varAnswer = 0; } NumberFunctions.prototype.addNumbers=function(NUM1, num2) { This. Answer = NUM1 +num2; } NumberFunctions.prototype.subtractNumbers=function(NUM1, num2) { This. Answer = NUM1-num2; } NumberFunctions.prototype.multiplyNUmbers=function(NUM1, num2) { This. Answer = NUM1 *num2; } NumberFunctions.prototype.divideNumbers=function(NUM1, num2) {if(num2! = 0) { This. Answer = NUM1/num2; } Else { This. Answer = 0; }} NumberFunctions.prototype.toString=function() {//the created object automatically calls the method return This. Answer; } varNF =Newnumberfunctions (); Nf.addnumbers (2, 1); Alert (NF);//NF automatically calls the ToString () methodNf.subtractnumbers (10, 3); Alert (NF); Nf.multiplynumbers (4, 5); Alert (NF); Nf.dividenumbers (12, 6); Alert (NF); /*The advantages are as follows: 1 There is no pollution to the global scope because there are numberfunctions functions; 2) All functions are actually members of the Numberfunctions class, so a clear relationship is constructed, 3) Basic object-oriented: functions of data and manipulation data It's all well encapsulated.*/
Object-oriented JS