将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
var shirt = function(params){
this.color = params && params.color || '无色';
this.size = params && params.size || 'big';
}
shirt.prototype = {
wear : function(){
console.log('Wear '+this.size+' and '+this.color+' shirt')
},
undress : function(){
console.log('Undress '+this.size+' and '+this.color+' shirt')
}
}
//衬衫类
var pants = function(params){
this.color = params && params.color || '无色';
this.size = params && params.size || 'big';
}
pants.prototype = {
wear : function(){
console.log('Wear '+this.size+' and '+this.color+' pants')
},
undress : function(){
console.log('Undress '+this.size+' and '+this.color+' pants')
}
}
//裤子类
var human = function(params,shirtParams,pantsParams){
this.name = params && params.name || 'Peter';
this.age = params && params.age || 18;
this.shirt = new shirt(shirtParams);
this.pants = new pants(pantsParams);
}
human.prototype = {
sayHello : function(){
console.log('Hello I am '+this.name);
},
sayAge : function(){
console.log('Hello I am '+this.age);
}
}
//人类
var peter = new human();
peter.sayHello();
peter.shirt.wear();
var jack = new human({name:'jack',age:30},{color:'red',size:'small'},{color:'yello',size:'small'})
jack.sayAge();
jack.pants.undress();