1)構造函數(shù)模式。
function Person(name, job) {
this.name = name
this.job = job
this.sayName = function() {
console.log(this.name)
}
}
var person1 = new Person('Jiang', 'student')
2)工廠模式
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("zhangsan",29,"soft engineer");
var person2 = createPerson("lisi",30,"hardware engineer");
3)原型模式
function Person(){}
Person.prototype.name="小米";
Person.prototype.showName=function(){
alert(this.name);
}
var person1=new Person();
person1.showName();
缺點:屬性共享
4)混合模型
構造函數(shù)模式定義實例屬性瑞侮,而原型模式用于定義方法和共享的屬性
function CreatePerson(name){
this.name=name;
}
CreatePerson.prototype.showName=function(){
alert(this.name);
}
var p1=new CreatePerson('小白');
p1.showName();
var p2=new CreatePerson('小綠');
p2.showName();