登录

javascript - 构造函数和工厂函数的区别

var Man;
Man = function(obj){
    if(!(this instanceof Man)){
        return new Man(obj);
    }
    this.attrObj = obj || {};//me.attrObj = {fullname:'xh'}
    this.wordsObj = [];
}
Man.prototype = {
    constructor:Man,
    words:function(){

    },
    attr:function(attribute,attributeValue){
        var defaultValue="<用户未输入>";
        if(arguments.length==2){
            console.log(1);
        }
        else if(!(attribute instanceof Object)){
            //看属性是不是对象,不是对象执行
            if((this.attrObj[attribute]===undefined)){
                return defaultValue;
            }
            else{
                return this.attrObj[attribute];
            }
        }
        else{
            //属性是对象那么赋值
            for(property in attribute){
                this.attrObj[prototype] = attribute[property];
            }
        }
    },
    say:function(){

    }
}
try{
    var me = Man({fullname:'小红'});//工厂模式
    var she = new Man({fullname:'小红'});//构造函数模式
    console.log(she);
    console.log(me)
    //请问这两个方式创建的对象又有啥区别呢,为什么常用下面的方式呢
}   
catch(e){
    console.error("执行出错,错误信息: " + e);
} 
# JavaScript
伊谢尔伦伊谢尔伦2216 天前426 次浏览

全部回复(2) 我要回复

  • 阿神

    阿神2017-04-10 17:20:29

    工厂函数和构造函数模式本来是有区别的,但你的例子里这两个模式合体了:

    if(!(this instanceof Man)){
        return new Man(obj);
    }

    这一句会判断,如果Man不是new调用的(此时函数体内的this是全局对象,而非Man的实例),就自动加个new
    所以你下面的meshe实际都是通过new调用的,虽然前者是通过工厂函数的形式,但函数内自动调用了new

    回复
    0
  • PHP中文网

    PHP中文网2017-04-10 17:20:29

    构造函数是类里面的,实例化(new)这个类的时候 ,会第一个调用构造函数,与之对应的有析构函数。

    工厂模式是一个设计模式。

    回复
    0
  • 取消回复发送