var lev=function(){ return "武林網(wǎng)"; }; function Parent(){ var Child = new Object(); Child.name="腳本"; Child.age="4"; Child.lev=lev; return Child; }; var x = Parent(); alert(x.name); alert(x.lev());
說明: 1.在函數(shù)中定義對象,并定義對象的各種屬性,,雖然屬性可以為方法,但是建議將屬性為方法的屬性定義到函數(shù)之外,這樣可以避免重復(fù)創(chuàng)建該方法 2.引用該對象的時候,這里使用的是 var x = Parent()而不是 var x = new Parent();因為后者會可能出現(xiàn)很多問題(前者也成為工廠經(jīng)典方式,后者稱之為混合工廠方式),不推薦使用new的方式使用該對象 3.在函數(shù)的最后返回該對象 4.不推薦使用這種方式創(chuàng)建對象,但應(yīng)該了解 第二種模式:構(gòu)造函數(shù)方式
var lev=function(){ return "武林網(wǎng)"; }; function Parent(){ this.name="腳本"; this.age="30"; this.lev=lev; }; var x =new Parent(); alert(x.name); alert(x.lev());