一、工厂模式
function createPerson(name,age,job){ var o=new Object(); o.name=name; o.age=age; o.job=job; o.sayHi=function(){ alert(this.name); }; return o; } var person1=createPerson("xiaoming",29,"student");
二、构造函数模式
function Person(name,age,job){ this.name=name; this.age=age; this.job=job; this.sayHi=function(){ alert(this.name); }; }; var person2=new Person("xiaohong",29,"doctor");
三、原型模式
function Person2(){}; Person2.prototype.name="xiaoming"; Person2.prototype.age=20; Person2.prototype.job="Doctor"; Person2.prototype.sayHi=function(){ alert("Hi!"); }; person4=new Person2(); person4.name="newPerson";
四、构造函数和原型的混血
function Person(name,age,job){ this.name=name; this.age=age; this.job=job; this.friends=["hebe","ella"]; }; Person.protoptype={ constructor:Person, sayName:function(){ alert(this.name); } } var person=new Person("xiaoming",20,"Doctor");
五、动态原型模式
function Person(name,age,job){ this.name=name; this.age=age; this.job=job; if(typeof this.sayName!="function"){ Person.prototype.sayName=function(){ alert(this.name); } }; }; var friend=new Person("xiaoming",20,"Doctor");
六、寄生构造函数——构造函数和工厂模式的混血
function Person(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 friend=new Person("hi",29,"Doctor");
七、稳妥构造函数
function Person(name,age,job){ var o=new Object(); o.sayName=function(){ alert(name); }; return o; }
var person=Person("xiaoming",20,"Doctor");