1. Factory function
functionrange (from, to) {varR =inherit (range.methods); R.from=From ; R.to=to ; returnR;}; Range.methods={includes:function(x) {return This. from <= x && x <= This. to; }, foreach:function(f) { for(varx = Math.ceil ( This. from); X <= This. to; X + +) f (x); }, ToString:function () { return"(" + This. from + "..." + This. to + ")"; }}//Here is example uses of a Range object.varR = Range (1, 3);//Create a Range objectR.includes (2);//= True:2 is in the rangeR.foreach (Console.log);//Prints 1 2 3Console.log (R);//Prints (1...3)
2. Use constructors instead of factory functions: Note that you must use the new operator when calling
functionRange (from, to) { This. from =From ; This. to =to ;} Range.prototype={includes:function(x) {return This. from <= x && x <= This. to; }, foreach:function(f) { for(varx = Math.ceil ( This. from); X <= This. to; X + +) f (x); }, ToString:function () { return"(" + This. from + "..." + This. to + ")"; } };//Here is example uses of a Range objectvarR =NewRange (1, 3);//Create a Range objectR.includes (2);//= True:2 is in the rangeR.foreach (Console.log);//Prints 1 2 3Console.log (R);//Prints (1...3)
3. Constructor properties
varF =function() {};//This is a function object.varp = f.prototype;//This is the prototype object associated with it.varc = p.constructor;//The the function associated with the prototype.c = = = F;//= = True:f.prototype.constructor==f for any functionvaro =NewF ();//Create An object o of Class FO.constructor = = = F;//= True:the Constructor property specifies the class
4, compare the following two paragraphs of the different code:
Range.prototype ={constructor:range,//explicitly set the constructor back-referenceIncludes:function(x) {return This. from <= x && x <= This. to; }, foreach:function(f) { for(varx = Math.ceil ( This. from); X <= This. to; X + +) f (x); }, ToString:function () { return"(" + This. from + "..." + This. to + ")"; }};/*a predefined prototype object that includes the constructor property*/Range.prototype.includes=function(x) {return This. from <= x && x <= This. to;}; Range.prototype.foreach=function(f) { for(varx = Math.ceil ( This. from); X <= This. to; X + +) f (x);}; Range.prototype.toString=function() {R
JavaScript authoritative Guide Notes (9th chapter classes and modules)