標籤:bsp 模組 成員方法 express with 靜態方法 blog process exp
最近在學習nodejs,就是因為它比較輕便,並發量大,上手快。由於以前一直在做C#的後端,沒有接觸過javascript,所以還得慢慢學習之。
nodejs所用的是javascript語言,它沒有如C#語言一樣正規正矩,倒是用起來還是比較方便。
要學習一門語言的初端,就要先學習其文法。今天學習nodejs的類型定義方式,以及怎樣匯出模組被其他js檔案require調用。
上代碼:
//在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();
執行結果:
"D:\Program Files (x86)\JetBrains\WebStorm 9.0.1\bin\runnerw.exe" "C:\Program Files\nodejs\node.exe" T4Express.jsshowAll 張思 23李四王武張三 21張三21Process finished with exit code 0
NodeJS類型定義方式