- 字面量式(最常用)
var person = {
name: 'xiaoming',
age: 18,
sayHello: function () {
console.log('hello', this.name)
}
}
- 調(diào)用系統(tǒng)的Object構(gòu)造函數(shù)颅和,創(chuàng)建實例對象
var person = new Object();
person.name = 'xiaoming'
person.age = 18
person.sayHello = function () {
console.log('hello', this.name)
}
- 工廠模式
function person (name, age) {
var obj = new Object()
obj.name = name
obj.age = age
obj.sayHello = function () {
console.log('hello', this.name)
}
return obj
}
var per = person('xiaoming', 18)
- 構(gòu)造函數(shù)模式
function Person (name, age) {
this.name = name;
this.age = age;
this.sayHello = function () {
console.log('hello', this.name)
}
}
var per = new Person('xiaoming', 18)
per.sayHello() //輸出 hello, xiaoming
與工廠模式的區(qū)別:
- 沒有顯式的創(chuàng)建對象
- 將屬性和方法直接賦給了this對象
- 沒有return語句
- 原型模式
function Person () {}
Person.prototype.name = 'xiaoming'
Person.prototype.age = 18
Person.prototype.sayHello = function () {
console.log('hello', this.name)
}
var per1 = new Person()
per1.sayHello() // 'hello, xiaoming'
var per2 = new Person ()
per2.sayHello() // 'hello, xiaoming'
- 組合使用構(gòu)造函數(shù)模式和原型模式(應(yīng)用最廣泛)
function Person (name, age) {
this.name = name;
this.age = age;
}
Person.prototype = {
constructor: Person,
sayHello = function () {
console.log('hello', this.name)
}
}
var per1 = new Person()
per1.sayHello() // 'hello, xiaoming'
- 動態(tài)原型模式
function Person (name, age) {
this.name = name;
this.age = age;
if (typeof this.sayHello !== 'function') {
Person.prototype.sayHello = function () {
console.log('hello', this.name)
}
}
}
var per = new Person ('xiaoming', 18)
per.sayHello()
注意
if(){}這段代碼只會在初次調(diào)用函數(shù)時才會執(zhí)行。其中锐极,if 語句檢查的可以是初始化之后應(yīng)該存在的任何屬性或方法嗽元,不必用一大堆 if 語句檢查每個屬性和每個方法;只要檢查其中一個即可邢羔。
- 寄生構(gòu)造函數(shù)模式
基本思想:創(chuàng)建一個函數(shù)篙骡,該函數(shù)的作用僅僅是封裝創(chuàng)建對象的代碼囚似,然后返回新創(chuàng)建的對象闻伶。
function Person (name, age) {
var o = new Object();
o.name = name;
o.age = age;
o.sayHello = function () {
console.log('hello', this.name)
}
return o;
}
var per = new Person('xiaoming', 18);
per.sayHello() // 'hello, xiaoming'
使用場景:
function CustomArray () {
var arr = new Array();
// 添加值
arr.push.apply(arr, arguments);
// 添加方法
arr.toPipedString = function () {
return this.join('|');
}
return arr;
}
var arr = new CustomArray(1,2,3,4,5)
arr.toPipedString()
- 穩(wěn)妥構(gòu)造函數(shù)模式
穩(wěn)妥對象指的是沒有公共屬性滨攻,而且其方法也不引用this的對象。
穩(wěn)妥構(gòu)造函數(shù)遵循與寄生構(gòu)造函數(shù)類似的模式蓝翰,不同處為:- 新創(chuàng)建對象的實例方法不引用this;
2.不使用new操作符調(diào)用構(gòu)造函數(shù)光绕;
穩(wěn)妥構(gòu)造函數(shù)與工廠模式的不同之處為,其方法不引用this的對象
- 新創(chuàng)建對象的實例方法不引用this;
function Person (name, age) {
var o = new Object();
o.sayName = function () {
console.log(name);
}
return o;
}
var per = Person('xiaoming', 18);
per.sayName()
注意:變量per中保存的是一個穩(wěn)妥對象畜份,用這種模式創(chuàng)建的對象诞帐,只能用sayName()訪問name的值。
穩(wěn)妥構(gòu)造函數(shù)模式提供的這種安全性爆雹,非常適合在某些安全執(zhí)行環(huán)境下使用停蕉,例如:ADsafe(www.adsafe.org)和 Caja(http://code.google.com/p/google-caja/)