javascript
JavaScript中的面向对象(1):对象创建模式
對(duì)象
JS中的對(duì)象是無(wú)序?qū)傩缘募?#xff0c;屬性可以包括基本值、對(duì)象、函數(shù)。簡(jiǎn)而言之,JS中的對(duì)象就是一組鍵值對(duì)。
創(chuàng)建對(duì)象
工廠模式
工廠模式是用函數(shù)將創(chuàng)建對(duì)象的細(xì)節(jié)封裝起來(lái)。
function createPerson(name){var o = new Object(); o.name = name; return o;}特點(diǎn):顯式地創(chuàng)建對(duì)象,有return
問(wèn)題:無(wú)法解決對(duì)象識(shí)別的問(wèn)題
構(gòu)造函數(shù)模式
類(lèi)似Object、Array等原生構(gòu)造函數(shù),我們可以自定義構(gòu)造函數(shù)。
function Person(name){ this.name = name; this.sayHello = function(){ alert('hello' + this.name)} }var person1 = new Person("Peter"); var person2 = new Person("Mike");特點(diǎn):不顯式地創(chuàng)建對(duì)象,沒(méi)有return,構(gòu)造函數(shù)的首字母大寫(xiě),不同實(shí)例之間具有相同的constructor屬性。
問(wèn)題:不同實(shí)例之間的同名函數(shù)不相等(具有不同的作用域鏈和標(biāo)識(shí)符解析)
解決:將函數(shù)的定義移到構(gòu)造函數(shù)外部。
問(wèn)題:sayHello定義在全局作用域,但實(shí)際上只能被某個(gè)對(duì)象調(diào)用。名不副實(shí)。2. 在需要定義很多方法的情況下,需要定義很多全局函數(shù),違背封裝的理念。
解決:原型模式
原型模式
每一個(gè)函數(shù)都有一個(gè)原型屬性,這個(gè)原型是一個(gè)指針,指向一個(gè)對(duì)象。
這個(gè)對(duì)象包含同一構(gòu)造函數(shù)所創(chuàng)建的所有實(shí)例所共享的屬性和方法。
事實(shí)上,上文提到的constrcutor屬性,也存在于原型對(duì)象中。
訪問(wèn)對(duì)象屬性時(shí),首先查找實(shí)例本身,然后查找原型對(duì)象。如果實(shí)例本身具有該屬性,就會(huì)屏蔽原型對(duì)象中的同名屬性。
用對(duì)象字面量來(lái)重寫(xiě)
function Person(){ }Person.prototype = { name:'Mike'; sayHello = function(){ alert('hello'+this.name); }此時(shí)
var mike = new Person mike.constructor == Person //false mike.constructor == Object //false更正:
Person.prototype = { constructor:Person name:'Mike'; sayHello = function(){ alert('hello'+this.name); }進(jìn)一步更正:
Object.defineProperty(Person.prototype,"constructor",{ enumerable: false, value:Person })構(gòu)造函數(shù)與原型模式組合
function Person(name){ this.name = name; this.friends = ['a','b']}Person.prototype = { constructor:Person; sayHello: function(){ alert('hello'+this.name) } }優(yōu)點(diǎn):每個(gè)實(shí)例擁有自己的屬性,不會(huì)互相干擾。
動(dòng)態(tài)原型模式
function Person(name){ this.name = name; this.friends = ['a','b']}if(typeof sayHello != function){ // 只需判斷一個(gè) Person.prototyp.sayHello = function(){ alert('hello'+this.name) } Person.prototyp.sayBye = function(){ alert('Bye'+this.name) } }優(yōu)點(diǎn):將所有信息封裝在構(gòu)造函數(shù)中,而只在第一次初始化時(shí),添加原型方法。
寄生構(gòu)造函數(shù)模式
在不改變某對(duì)象原型的情況下,添加新的方法。
function SpecialArray(){var values = new Array();values.toPipedString = function(){ return this.join('|'); }return values;}缺點(diǎn):對(duì)象與構(gòu)造函數(shù)之間沒(méi)有關(guān)系,不能使用instanof操作符。
穩(wěn)妥構(gòu)造函數(shù)模式
function Person(name){ var o = new Object(); o.sayName = function(){ alert(name) } return o; }var mike = Person('mike');特點(diǎn):不使用new操作符,實(shí)例方法中不引入this。
缺點(diǎn):對(duì)象與構(gòu)造函數(shù)之間沒(méi)有關(guān)系,不能使用instanof操作符。
轉(zhuǎn)載于:https://www.cnblogs.com/cogons/p/6628985.html
總結(jié)
以上是生活随笔為你收集整理的JavaScript中的面向对象(1):对象创建模式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Logstash之Logstash in
- 下一篇: JS实现单例模式