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

查看:121
本文介绍了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);
} 

解决方案

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

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

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

这篇关于javascript - 构造函数和工厂函数的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆