1.工廠模式
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 person = createPerson("Greg", 27, "Doctor");
2.構造函數模式
//構造函數首字母大寫
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
//當做構造函數使用
var person = new Person("Greg", 27, "Doctor");
person.sayName(); // "Greg"
//作爲普通函數調用
Person("Greg",27,"Doctor");
window.sayName(); // "Greg"
//使用new操作符來調用構造函數,則創建新對象,並且屬性和方法都賦給指定的對象,如果不用new操作符,則將屬性和方法賦給window對象。
3.原型模式
我們創建的每個函數都有一個prototype(原型)屬性,這個屬性是一個指針,指向一個對象,而這個對象的用途是包含可以由特定類型的所有實例共享的屬性和方法。
function Person(){
}
Person.prototype.name = "Greg";
Person.prototype.age = 29;
Person.prototype.job = "Doctor";
Person.prototype.sayName = function(){
alert(this.name);
}
var person = new Person();
person.sayName();
通過原型模式創建的對象,所有的屬性都是一樣的 。
4.動態原型模式
該模式是把所有信息都封裝到構造函數中,通過構造函數中初始化原型(僅在必要的情況下),又保持了同時使用構造函數和原型的優點
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("Greg",20,"Doctor");
frient.sayName();