面向物件(建立物件)--七種模式總結
阿新 • • 發佈:2018-12-13
工廠模式(工廠模式雖然解決了建立多個相似物件的問題,但卻沒有解決物件識別的問題(即怎樣知道一個物件的型別))
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("Nicholas", 29, "Software Engineer"); var person2 = createPerson("Greg", 27, "Doctor");
建構函式模式(在全域性作用域中定義的函式實際上只能被某個物件呼叫;如果物件需要定義很多方法,那麼就要定義很多個全域性函式)
function Person(name, age, job) { this.name = name; this.age = age; this.job = job; this.sayName = sayName; } function sayName() { alert(this.name); } var person1 = new Person("Nicholas", 29, "Software Engineer"); var person2 = new Person("Greg", 27, "Doctor");
原型模式(引用型別存在弊端)
function Person() {} Person.prototype = { name: "Nicholas", age: 29, job: "Software Engineer", sayName: function() { alert(this.name); } }; // 重設建構函式,只適用於 ECMAScript 5 相容的瀏覽器 Object.defineProperty(Person.prototype, "constructor", { enumerable: false, value: Person });
組合使用建構函式模式和原型模式(認可度最高)
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Shelby", "Court"];
}
Person.prototype = {
constructor: Person,
sayName: function() {
alert(this.name);
}
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
person1.friends.push("Van");
alert(person1.friends); //"Shelby,Count,Van"
alert(person2.friends); //"Shelby,Count"
alert(person1.friends === person2.friends); //false
alert(person1.sayName === person2.sayName); //true
動態原型模式
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("Nicholas", 29, "Software Engineer");
friend.sayName();
寄生建構函式模式
function Person(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 friend = new Person("Nicholas", 29, "Software Engineer");
friend.sayName(); //"Nicholas"
穩妥建構函式模式
function Person(name, age, job) {
//建立要返回的物件
var o = new Object();
//可以在這裡定義私有變數和函式
//新增方法
o.sayName = function() {
alert(name);
};
//返回物件
return o;
}
var friend = Person("Nicholas", 29, "Software Engineer");
friend.sayName(); //"Nicholas"