簡體   English   中英

module.export在nodejs中的函數

[英]module.exports a function in nodejs

我想將功能和變量從一個文件(模塊)導出到另一個文件(模塊)。 就是這樣

    // animals.js 
        function weight () {
         return "90kgs"; 
    }
    module.exports = weight();

    // tiger.js 
    var animal = require('./animals.js');
    module.exports = { 
             'animalWeight' : function animal.weight(),
             'stripes' : true 
    }


   // zoo.js
   var tiger = require('./tiger.js');
   tiger.animalWeight(); // should return 90kgs
   tiger.stripes ; // should return true

如何實現以上。 我收到以下錯誤

   'animalWeight' : function animal.weight(),
                                   ^
    SyntaxError: Unexpected token .

導出函數時,需要引用它

function weight () {
     return "90kgs"; 
}
module.exports = weight;

現在,當您導入它時,您將獲得該函數,並可以再次引用它

var animal = require('./animals.js');

module.exports = { 
    'animalWeight' : animal,
    'stripes' : true 
}

當您再次導入時,可以調用該函數

var tiger = require('./tiger.js');

tiger.animalWeight(); // "90kgs"
tiger.stripes ; // true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM