[javascript]
//工厂模式
function Person1(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
return o;
}
var p1 = Person1('Mukti',30,'FE Engineer');
//构造函数模式
function Person2(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
var p2 = new Person2('Mukti',30,'FE Engineer');
// 原型模式
function Person3(){}
Person3.prototype.name = 'Mukti';
Person3.prototype.age = 29;
Person3.prototype.job = 'FE Engineer';
Person3.prototype.sayName = function(){
alert(this.name);
};
var p3 = new Person3();
// 组合构造函数模式和原型模式
function Person4(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.friends = ['Laura','Faust'];
}
Person4.prototype = {
constructor:Person4,
sayName:function(){
alert(this.name);
}
}
// 动态原型模式
function Person5(name, age, job){
this.name = name;
this.age = age;
this.job = job;
if(typeof this.sayName != 'function'){
Person5.prototype.sayName = function(){
alert(this.name);
}
}
}
// 寄生构造函数模式
function Person6(name, age, job){
var o = Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
}
return o;
}
// 稳妥构造函数模式
[/javascript]
您的赞助将会支持作者创作及本站运维
发表评论