码迷,mamicode.com
首页 > 编程语言 > 详细

javascript权威指南笔记(第9章 类和模块)

时间:2014-09-10 22:21:51      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   os   使用   java   ar   

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

 

javascript权威指南笔记(第9章 类和模块)

标签:des   style   blog   color   io   os   使用   java   ar   

原文地址:http://www.cnblogs.com/liguwe/p/3965185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!