NodeJS類型定義方式

來源:互聯網
上載者:User

標籤: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類型定義方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.