1、工厂函数
function range(from, to) { var r = inherit(range.methods); r.from = from; r.to = to; return r; }; range.methods = { includes: function (x) { return this.from <= x && x <= this.to; }, foreach: function (f) { for (var x = Math.ceil(this.from); x <= this.to; x++) f(x); }, toString: function () { return "(" + this.from + "..." + this.to + ")"; } } // Here are example uses of a range object. var r = range(1, 3); // Create a range object r.includes(2); // => true: 2 is in the range r.foreach(console.log); // Prints 1 2 3 console.log(r); // Prints (1...3)
2、使用构造函数代替工厂函数: 注意调用时必须使用new操作符
function Range(from, to) { this.from = from; this.to = to; } Range.prototype = { includes: function (x) { return this.from <= x && x <= this.to; }, foreach: function (f) { for (var x = Math.ceil(this.from); x <= this.to; x++) f(x); }, toString: function () { return "(" + this.from + "..." + this.to + ")"; } }; // Here are example uses of a range object var r = new Range(1, 3); // Create a range object r.includes(2); // => true: 2 is in the range r.foreach(console.log); // Prints 1 2 3 console.log(r); // Prints (1...3)
3、constructor属性
var F = function() {}; // This is a function object. var p = F.prototype; // This is the prototype object associated with it. var c = p.constructor; // This is the function associated with the prototype. c === F; // => true: F.prototype.constructor==F for any function var o = new F(); // Create an object o of class F o.constructor === F; // => true: the constructor property specifies the class
4、比较下面两段代码的不同:
Range.prototype = { constructor: Range, // Explicitly set the constructor back-reference includes: function (x) { return this.from <= x && x <= this.to; }, foreach: function (f) { for (var x = Math.ceil(this.from); x <= this.to; x++) f(x); }, toString: function () { return "(" + this.from + "..." + this.to + ")"; } }; /*预定义原型对象,这个原型对象包括constructor属性*/ Range.prototype.includes = function (x) { return this.from <= x && x <= this.to; }; Range.prototype.foreach = function (f) { for (var x = Math.ceil(this.from); x <= this.to; x++) f(x); }; Range.prototype.toString = function () { r
时间: 2024-10-18 08:28:00