首页 > 代码库 > 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章 类和模块)