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")
優(yōu)點(diǎn): 能快速的構(gòu)建大量實(shí)例。
缺點(diǎn): 不能解決對(duì)象識(shí)別的問(wèn)題汪茧。
2. 構(gòu)造函數(shù)模式
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")
優(yōu)點(diǎn): 能快速構(gòu)建大量, 可以將其實(shí)例標(biāo)識(shí)為一種特定類型
缺點(diǎn): 每個(gè)方法都要在每個(gè)實(shí)例上重新創(chuàng)建一遍
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")
簡(jiǎn)寫
function Person() {}
Person.prototype = {
constructer: Person,
name: "wst",
age: '22',
job: 'web'
};
優(yōu)點(diǎn):避免了相同方法的重復(fù)構(gòu)建
缺點(diǎn):因?yàn)槠涔蚕淼谋举|(zhì),影響到實(shí)例擁有自己的全部屬性
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")
使用最廣泛,認(rèn)同度最高葛假,定義引用類型的一種默認(rèn)模式