zoukankan      html  css  js  c++  java
  • nodejs中引用其他js文件中的函数--转载

    原地址 : https://www.cnblogs.com/wuotto/p/9640312.html

    基本语句

    require('js文件路径');

    使用方法

    举个例子,在同一个目录下,有appfun1fun2三个js文件。

    1. app.js

    var fun1 = require('./fun1');
    var fun2 = require('./fun2');
    
    function test(){
         console.log("调用了app的test方法");
         fun1.add(1,2);
         fun2();
    }
         test();
    

      

    2. fun1.js

    function reduce(a,b){
        console.log("调用了fun1的reduce方法");
        console.log(a-b);
    }
    
    function add(a,b){
        console.log("调用了fun1的add方法");
        console.log(a+b);
    }
    module.exports = {
     reduce,
     add
    }

    3. fun2.js

    module.exports = function  print(){
        console.log("调用了fun2的print方法");
    }
    
    这种的调用方法为: fun2();
    
    或者
    
    
    module.exports = {
        print:function(){
            console.log("调用了fun2的print方法");
        },
        copy:function(a,b){
              console.log("我是fun2的copy方法");
        }
    }
    
    这种的调用方法为:fun2.print();
    

    可以看到fun1fun2的写法略有不同,fun1这种写法更好,因为它可以只把别的文件需要调用的函数导出,未导出的函数别的js文件是用不了的

    输出结果如下

    调用了app的test方法
    调用了fun1的add方法
    3
    调用了fun2的print方法
     
    程序开发机器人 琴酒、灰原哀、刺痛是我心尖尖上的人 最爱琴酒、灰原哀、刺痛
  • 相关阅读:
    块级元素与行级元素(内联元素)
    css中属性值继承小解
    form表单
    html,xhtml和xml
    html中的标签分类
    如何把HTML标记分类
    实现对HashMap的value排序
    装饰者模式
    实现一个简单的二叉树容器,并且实现中序、先序、后续遍历
    Java中java.util.concurrent包下的4中线程池代码示例
  • 原文地址:https://www.cnblogs.com/doudou0809/p/14040930.html
Copyright © 2011-2022 走看看