工厂函数与构造函数

 

 工厂函数

<script>
    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;
        },
        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);
</script>

构造函数

<script>
    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 x=Math.ceil(this.from);x<this.to;x++) f(x);
        },
        toString:function(){
            return this.from+'...'+this.to
        }
    };
    
    var r=new Range(1,3);
    console.log(r.includes(2));
    r.foreach(console.log);
    console.log(r);
</script>

 区别:

1、构造函数首字母大写,必须通过关键字new。

权威指南204页的部分解释:在调用构造函数之前就已经创建了新对象,通过this关键字可以获取新创建的对象。Range()构造函数只不过是初始化this而已。构造函数甚至不必返回这个新创建的对象,构造函数会自动创建对象,然后将构造函数作为这个对象的方法来调用一次,最后返回这个新对象。

2、原想对象的命名。

工厂函数是range.methods这个岁随意命名的。

构造函数是Range.prototype这是强制必须这样写。

原文地址:https://www.cnblogs.com/gaidalou/p/5980909.html