javascript 创建类 属性 和方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangtao510/article/details/55511421
方法一————————————————————————————————————————————————————————————
function Range(from, to) { 
    this.from = from;
    this.to = to; 
}


Range.prototype = {
    includes: function (x) {
        return this.from <= x && this.to >= x;
    },
    foreach: function (f) {
        for (var b = Math.ceil(this.from); b <= this.to; b++) f(b);
    },
    toString: function () { return "(" + this.from + "----" + this.to + ")"; }
};
方法二:————————————————————————————————————————————————————————————  
//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 && this.to >= x;
    },
    foreach: function (f) {
        for (var b = Math.ceil(this.from); b <= this.to; b++) f(b);
    },
    toString: function () { return "(" + this.from + "----" + this.to + ")"; }
};

//通过原型继承创建一个新对象
function inherit(p) {
    if (p == null) throw TypeError();
    if (Object.create) {
        return Object.create(p);
    }

    var t=typeof p;
    if(t!="object" && t!="function")throw TypeError();
    function f(){};
    f.prototype=p;
    return f;
}

测试—————————————————————————————————————————————————————————————————————

            var r = new Range(1, 3);
            r.includes(2);
            r.foreach(function (x) { alert(x); });
            alert(r);


猜你喜欢

转载自blog.csdn.net/wangtao510/article/details/55511421
今日推荐