node.js的模組引用

來源:互聯網
上載者:User

標籤:incr   module   模組   一個   com   length   引入   樣本   var   

1.模組的引用樣本

      var      math   =    require(‘math’);

在common.js規範中,存在require()方法,這個方法接受模組標識,此引引入一個模組的api 到當前的上下文中。

2.模組定義

       在模組中,上下文提供require()方法來引入外部模組。對應引入的功能,上下文提供了exports對象用於到處當前模組的方法或者變數,並且它是唯一到處的出口,在模組中,還存在一個module對象,他代表模組自身,而exports是module的屬性。在node中,一個檔案就是一個模組,講方法掛載在exports對象上作為屬相即可定義匯出的方式:

 

   //math.js

    exports.add =  function(){

  var    sum = 0,

  i = 0,

  args = arguments,

  l = args.length

  while(i < 1){

     sum += args[i ++ ];

       };

          return     sum;

    };

在另一個檔案中,我們通過require()方法引入模組後,就能調用定義的屬性或方法了:、

 //program.js

  var   math = require(‘math‘);

  exports.increment = function(val){

    return  math.add(val , 1);  

};

node.js的模組引用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.