Nodejs require 一个模块的 new 问题
Nodejs require 一个模块的 new 问题
//module.js
var name;
exports.setName = function(thyName) {
name = thyName;
};
exports.sayHello = function() {
console.log('Hello ’ + name);
};
var myModule = require(’./module’);
myModule.setName(‘BYVoid’);
myModule.sayHello();
function Hello() {
var name;
this.setName = function(thyName) {
name = thyName;
};
this.sayHello = function() {
console.log('Hello ' + name);
};
};
module.exports = Hello;
var Hello = require(’./singleobject’);
hello = new Hello();
hello.setName(‘BYVoid’);
hello.sayHello();
这里第一个 require
一个模块后不需要 new
,第二个为什么要 new
一个呢?请教各位大神一下,谢谢
在Node.js中,require
用于加载模块。不同的模块可能有不同的实现方式,这导致了在某些情况下需要使用 new
关键字来创建实例,而在其他情况下则不需要。
让我们详细分析你提供的代码示例:
示例1: module.js
// module.js
var name;
exports.setName = function(thyName) {
name = thyName;
};
exports.sayHello = function() {
console.log('Hello ' + name);
};
在这个例子中,module.js
导出的是两个函数(setName
和 sayHello
),而不是一个类或构造函数。因此,当你在 getmoudle.js
中使用 require
加载这个模块时,返回的对象是一个普通的 JavaScript 对象,你可以直接调用它的方法:
// getmoudle.js
var myModule = require('./module');
myModule.setName('BYVoid');
myModule.sayHello(); // 输出 "Hello BYVoid"
示例2: hello.js
// hello.js
function Hello() {
var name;
this.setName = function(thyName) {
name = thyName;
};
this.sayHello = function() {
console.log('Hello ' + name);
};
};
module.exports = Hello;
在这个例子中,hello.js
导出的是一个构造函数 Hello
。为了使用这个构造函数创建一个新的对象实例,你需要使用 new
关键字:
// gethello.js
var Hello = require('./hello');
var hello = new Hello();
hello.setName('BYVoid');
hello.sayHello(); // 输出 "Hello BYVoid"
总结
- 不需要
new
的情况:当模块导出的是一个普通对象(包含方法和属性)时,你不需要使用new
。 - 需要
new
的情况:当模块导出的是一个构造函数时,你需要使用new
来创建该构造函数的一个实例,以便调用其方法和访问其属性。
通过这种方式,你可以更好地理解何时需要使用 new
关键字来处理 Node.js 模块。
也可以不用 new
的, new
到底是干嘛的, 是 JavaScript 的基本语法, 你可以去学习 JavaScript 关于原型 prototype 的基础知识
jsfunction dog() {
this.wanwan = function(){
alert("汪汪");
};
}
var dg = new dog();
dg.wanwan();
好的,谢谢回复了
这不是 require 的知识范畴。应该去看看 js 里面的 new 是干嘛的。
在Node.js中,使用require
加载模块时是否需要使用new
关键字取决于模块导出的内容。
- 在第一个例子(
module.js
)中,导出的是对象,而不是类。exports
对象是普通对象,包含了两个方法:setName
和sayHello
。因此,在使用require
时,可以直接调用这些方法,而不需要使用new
关键字。
// getmoudle.js
var myModule = require('./module');
myModule.setName('BYVoid'); // 直接调用对象的方法
myModule.sayHello();
- 在第二个例子(
hello.js
)中,导出的是一个构造函数(即类)。Hello
函数可以被看作是一个类,其中定义了两个方法:setName
和sayHello
。当使用require
加载该模块时,返回的是这个构造函数,因此你需要通过new
关键字来创建实例,并使用这些方法。
// gethello.js
var Hello = require('./hello'); // 导出的是一个构造函数
var hello = new Hello(); // 使用 new 创建实例
hello.setName('BYVoid');
hello.sayHello();
总结来说,如果你导出的是一个普通的对象(包含方法),那么在使用require
时直接调用方法即可;如果你导出的是一个构造函数(类),则需要使用new
关键字来创建实例。