javascript對(duì)象封裝的方法:1、使用常規(guī)封裝,代碼為【function Person (name,age,sex)】;2、常見(jiàn)的方法,代碼為【constructor : Person,_init_ :function(info)】。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版,DELL G3電腦。
javascript對(duì)象封裝的方法:
常規(guī)封裝
function Person (name,age,sex){ this.name = name; this.age = age; this.sex = sex; } Pserson.prototype = { constructor:Person, sayHello:function(){ console.log('hello'); } }
這種方式是比較常見(jiàn)的方式,比較直觀,但是Person() 的職責(zé)是構(gòu)造對(duì)象,如果把初始化的事情也放在里面完成,代碼就會(huì)顯得繁瑣,如果放在一個(gè)方法里初始化會(huì)不會(huì)好點(diǎn)呢?
升級(jí)版 (常見(jiàn))
function Person (info){ this._init_(info); } Pserson.prototype = { constructor : Person, _init_ : function(info) { this.name = info.name; this.age = info.age; this.sex = info.sex; } sayHello:function(){ console.log('hello'); } }
可是,說(shuō)到這里就發(fā)現(xiàn),name,age,sex 并沒(méi)有在Person里面申明,哪來(lái)的呢???
相關(guān)免費(fèi)學(xué)習(xí)推薦:javascript視頻教程