zoukankan      html  css  js  c++  java
  • js中:类、原型、构造函数

    // 使用inherited函数创建对象  这个对象继承原型对象中
    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 new f();
    };
    // 这个工厂方法返回一个心得"范围对象"
    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;
        },
        // 对于范围内得每个整数都调用一次f
        // 这个方法只可用做数字范围。
        foreach: function (f) {
            for (var x = Math.ceil(this.from); x <= this.to; x++) f(x);
        },
        toString: function () {return "(" + this.from + "..." + this.to + ")";}
    }

    var r = range(1, 3); //创建一个范围对象

    console.log(r.includes(2));
    r.foreach(console.log);
    console.log(r);
    // ----------使用构造函数来定义 ”范围类“------------

    function Range(from, to) {
        // 储存  范围对象 得其实位置 喝结束位置
        // 这两个属性是不可继承得, 没个对象都拥有唯一得属性
        this.from = from;
         this.to = to;
    };
    //所有得 范围独享 都继承自这个对象
    // 这个属性得名字必须是 prototype
    Range.prototype = {
        // 如果下再范围内, 则返回true 否则 false
        // 这个方法可比较数字范围,也可以比较字符串和日期范围
        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 + ")";}
    }
  • 相关阅读:
    poj 1328 Radar Installation (贪心)
    hdu 2037 今年暑假不AC (贪心)
    poj 2965 The Pilots Brothers' refrigerator (dfs)
    poj 1753 Flip Game (dfs)
    hdu 2838 Cow Sorting (树状数组)
    hdu 1058 Humble Numbers (DP)
    hdu 1069 Monkey and Banana (DP)
    hdu 1087 Super Jumping! Jumping! Jumping! (DP)
    必须知道的.NET FrameWork
    使用记事本+CSC编译程序
  • 原文地址:https://www.cnblogs.com/stevenzhangcy/p/10795857.html
Copyright © 2011-2022 走看看