首页 > 代码库 > javascript权威指南笔记(第9章 类和模块)
javascript权威指南笔记(第9章 类和模块)
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 objectr.includes(2); // => true: 2 is in the ranger.foreach(console.log); // Prints 1 2 3console.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 objectvar r = new 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)
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 functionvar o = new F(); // Create an object o of class Fo.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
javascript权威指南笔记(第9章 类和模块)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。