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