首页 > Web开发 > 详细

11-《Node.js开发指南》模块和包

时间:2019-12-21 10:36:42      阅读:94      评论:0      收藏:0      [点我收藏+]

什么是模块?

一个node.js文件就是一个模块,这个文件可能是js代码,json或者编译过的C/C++扩展

创建及加载模块

//a.js
var name;
exports.setName = function(thyName){
    name = thyName;
};
exports.sayHello = function(){
    console.log("hello"+name);
};
//b.js
var myModule =  require('./a.js');
myModule.setName('柠檬不酸');
myModule.sayHello();

对象封装到模块中

第一种

function Hello(){
    var name;
    this.setName = function (thyName){
        name=thyName;
    }
    this.sayHello = function(){
        console.log('hello'+name)
    }
}
exports.Hello=Hello;
var Hello = require('./c.js').Hello;
hello = new Hello();
hello.setName('柠檬不酸le');
hello.sayHello();

第二种

//c.js
function Hello(){
    var name;
    this.setName = function (thyName){
        name=thyName;
    }
    this.sayHello = function(){
        console.log('hello'+name)
    }
}
module.exports = Hello;
//d.js
var Hello = require('./c.js');
hello = new Hello();
hello.setName('柠檬不酸');
hello.sayHello();
注意:不可以通过exports 直接赋值代替对module.exports赋值;
exports实际上只是一个和module.exports指向同一个对象的变量,它本身会在模块执行结束后释放,但module不会,因此只能通过指定module.exports来改变访问接口;

11-《Node.js开发指南》模块和包

原文:https://www.cnblogs.com/foreverLuckyStar/p/12076111.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!