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);
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
工厂函数和构造函数模式本来是有区别的,但你的例子里这两个模式合体了:
这一句会判断,如果
Man不是new调用的(此时函数体内的this是全局对象,而非Man的实例),就自动加个new。所以你下面的
me和she实际都是通过new调用的,虽然前者是通过工厂函数的形式,但函数内自动调用了new。构造函数是类里面的,实例化(new)这个类的时候 ,会第一个调用构造函数,与之对应的有析构函数。
工厂模式是一个设计模式。