工廠模式、建構函式模式、原型模式範例
阿新 • • 發佈:2019-02-12
/**
* Created by chen on 2015/10/29.
*/
//工廠模式
function createPerson(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 person1 = createPerson("Nichols",21,"software engineer");
var person2 = createPerson("Greg",34,"teacher");
alert(person1.name);
alert(person2.job);
//建構函式模式
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
var person3 = new Person("Nichols",21,"nnn" );
var person4 = new Person("chench",32,"teacher");
//原型模式
function Pperson(){
}
Pperson.prototype.name = "Nichlos";
Pperson.prototype.age = 29;
Pperson.prototype.job = "dfs";
Pperson.prototype.sayName = function(){
alert(this.name);
}
var person5 = new Pperson();
person5.sayName();