下面通過文字詳解加代碼分析,分享 JavaScript 設計模式中對象工廠函數與構造函數的相關知識。
概述:使用對象字面量,或向空對象動態添加成員,是最簡單易用的建對象方式。除此之外,JavaScript 還提供了其他方法。
1)使用工廠函數創建對象
我們可以寫一個專門創建對象的函數,稱之為「對象工廠方法」。
代碼如下:
//工廠函數
function createPerson(name, age, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function () {
console.info(this.name);
};
return o;
}
//使用工廠函數創建對象
var person1 = createPerson('張三', 29, '軟件工程師');
var person2 = createPerson('李四', 40, '醫生');
2)定義對象構造函數
要點:a) 構造函數首字母大寫;b) 內部用 this 給對象添加成員;c) 用 new 調用。
代碼如下:
//定義對象「構造」函數
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function () {
console.info(this.name);
};
}
//使用 new 調用對象構造函數創建對象
var p1 = new Person('張三', 29, '軟件工程師');
var p2 = new Person('李四', 40, '醫生');
以普通方式調用的「構造函數」
構造函數本質也是函數,區別在於調用時必須加 new,否則就被當作普通函數調用。
代碼如下:
//作為普通函數調用的構造函數,通過 this 添加的屬性,
//成為了 window 對象的屬性與方法。
console.info(window.name);//張三
console.info(window.age); //29
console.info(window.job); //軟件工程師
對象構造函數長這樣:
function Person (name) {
this.name = name;
this.say = function () {
return "I am " + this.name;
};
}
實際上是這樣(示意):
function Person (name) {
// var this = {};
this.name = name;
this.say = function () {
return "I am " + this.name;
};
// return this;
}
構造函數完成的工作:
1. 創建一個新對象
2. 讓構造函數的 this 引用這個新對象
3. 執行構造函數中的代碼,通常完成向新對象添加屬性
4. 向外界返回新對象的引用
對象構造函數與工廠方法的區別:
1. 構造函數中沒有顯式的對象創建代碼
2. 新對象的屬性與方法通過 this 添加
3. 構造函數中沒有 return 語句
通常會把構造函數首字母大寫,以區別普通函數。
對象的 constructor 屬性
a) 用工廠函數創建的對象,其 constructor 引用 Object()
var person = createPerson('張三', 29, '軟件工程師');
//使用工廠方法創建對象,其 constructor 屬性引用 Object() 函數
console.info(person1.constructor === Object);//true
b) 用構造函數創建的對象,其 constructor 引用該構造函數
var p = new Person('張三', 29, '軟件工程師');
//每個對象的 constructor 屬性,引用這個構造函數
console.info(p.constructor === Person);//true
如何避免「忘記」new?可用 arguments.callee 解決。先了解它的作用:
function TestArgumentsCallee()
{
console.info(this);
console.info(this instanceof TestArgumentsCallee);
console.info(this instanceof arguments.callee);
};
TestArgumentsCallee(); //window
//false
//false
new TestArgumentsCallee();
//TestArgumentsCallee
//true
//true
於是可直接用 arguments.callee:
//避免忘記 new
function MyObject(value)
{
if (!(this instanceof arguments.callee))
{
//如果調用者忘記加上 new 了,就加上 new 再調用一次
return new MyObject(value);
}
this.prop = value;
}
//測試
var obj1 = new MyObject(100);
console.info(obj1.prop);//100
var obj2 = MyObject(200);
console.info(obj2.prop); //200
以上就是 JavaScript 設計模式中對象工廠函數與構造函數的詳解,希望大家喜歡。