//在nodejs中,類型定義就像定義函數一樣,其實該函數就是Student類的構造函數 var Student=function(){ //如果需要定義該類對象的字段、方法等,需加上this關鍵字,否則就認爲是該函數中的臨時變量 this.Name="張三"; this.Age=21; //定義對象方法 this.show=function(){ console.log(this.Name+' '+this.Age); }; }; //類的成員方法也可以在構造方法外定義,需加上prototype關鍵字,否則就認爲是定義類方法(靜態方法) Student.prototype.showName=function(){ console.log(this.Name); }; Student.prototype.showAge=function(){ console.log(this.Age); }; //定義類方法(類的靜態方法,可直接通過類名訪問) Student.showAll=function(name,age){ console.log("showAll "+name+' '+age); }; //定義類的靜態字段 Student.TName="李四"; //導出Student類,使其他js文件可以通過require方法類加載該Student模塊 module.exports=Student;
其他js中訪問student
//使用require方法加載Student模塊 var student=require('./Student'); //調用類方法 student.showAll("張思",23); //展現類靜態字段 console.log(student.TName); student.TName="王武"; console.log(student.TName); //實例化類對象 var stu=new student(); stu.show(); stu.showName(); stu.showAge();
通過上述例子可以看出,加上關鍵字prototype表示該變量或者函數是類的成員變量或者成員函數,調用需要new出這個對象。而沒有prototype該關鍵字修飾的變量或者函數,相當於靜態變量或者靜態函數,可以在外部跟上類名直接調用。