1. 工廠模式
function makeObj(name, age, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayAge = function() {
alert(this.age);
};
return o;
}
var a = makeObj("wst", "22", "web")
優點: 能快速的構建大量實例。
缺點: 不能解決對象識別的問題。
2. 構造函數模式
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayAge = function() {
alert(this.age);
};
}
var a = new Preson("wst", "22", "web")
優點: 能快速構建大量, 可以將其實例標識為一種特定類型
缺點: 每個方法都要在每個實例上重新創建一遍
3. 原型模式
function Person() {
}
Person.prototype.name = 'wst';
Person.prototype.age = '22';
Person.prototype.job = 'web';
Person.prototype.sayAge = function() {
alert(this.age);
};
var a = new Preson("wst", "22", "web")
簡寫
function Person() {}
Person.prototype = {
constructer: Person,
name: "wst",
age: '22',
job: 'web'
};
優點:避免了相同方法的重復構建
缺點:因為其共享的本質,影響到實例擁有自己的全部屬性
4.混合模式
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
this.frisds = ['zkw','lyf'];
}
Person.prototype = {
constructor:Person,
sayName:function (){
alert(this.name);
}
};
var a = new Preson("wst", "22", "web")
使用最廣泛,認同度最高,定義引用類型的一種默認模式