学node的一点小笔记(五) node的模块与引用

本文介绍了Node.js中模块的创建与使用方法,包括如何通过module.exports导出模块功能及如何利用require加载并实例化模块。同时展示了如何将函数作为参数传递给另一个函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

node的模块与引用

module.js

//直接封装函数,可以在引用的js处调用
exports.world = function(){
console.log('hello')
}

//只是把一个对象封装到模块中:
function hello(){
var name = '111'
this.setName = function(newName){
name = newName
}
this.sayHello = function(){
console.log('hello'+name)
}
}
module.exports = hello;


require.js

//引入模块
//node遵循commonJs语法,不能用import和define
var hello = require ('./module');
console.log(hello)

//实例化一个hello对象,不实例化无法应用
var hell = new hello();
hell.setName('222');
hell.sayHello()

//Node.js函数
function xx(someFunction,someValue){
someFunction(someValue)
}
//第一个参数是某函数,第二个是传递的值
xx(hell.setName,'444')
xx(hell.sayHello)

//匿名函数
xx(function(word){
console.log(word)
},'eee')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值