JavaScript Tutorial 05 #Class#

/* range.js */
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 + ")";
    }
};

//普通函数首字母小写, 定义类首字母大写
function Range(from, to) {
    this.from = from;
    this.to = to;
}
Range.prototype = {

};

/* Complex.js */
function Complex(real,imgainary) {
    if(isNaN(real) || isNaN(imgainary)) {
        throw new TypeError();
    }
    this.r = real;
    this.i = imgainary;
}

Complex.prototype.add = function(that) {
    return new Complex(this.r + that.r, this.i + that.i);
};
/* 类字段 */
Complex.parse = function(s) {
    try {
        var m = Complex._format.exec(s);
        return new Complex(parseFloat(m[1]), parseFloat(m[2]));
    } catch(x) {
        throw new TypeError("Can't parse '" + s + "' as a complex number.");
    }
};
Complex._format = /^{([^,]+),([^}]+)}$/;

原文地址:https://www.cnblogs.com/lambdatea/p/3377939.html