JS是一門(mén)面向?qū)ο笳Z(yǔ)言,其對(duì)象是用prototype屬性來(lái)模擬的,下面,來(lái)看看如何封裝JS對(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:func