要求如何与Node.js中的新运算符一起使用? [英] How does require work with new operator in node.js?

查看:95
本文介绍了要求如何与Node.js中的新运算符一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们用以下代码创建一个file.js:

Let's have a file.js with this code:

module.exports.func = function(txt) {
    this.a = 1;
    this.b = 2;
    console.log(txt, this);
    return this;
}

现在我们有另一个JS文件,我们在其中执行以下操作:

Now we have another JS file where we do following:

var r1 = new (require('./file')).func('r1');
var r2 = new require('./file').func('r2');

在r1情况下,它可以按预期工作-r1包含对新创建对象的引用.

In r1 case it works as intended - r1 contains reference to the newly created object.

在r2情况下,它不起作用-r2从file.js中获取对module.exports的引用.

In r2 case it does not work - r2 gets reference to module.exports from within the file.js.

目的是通过调用func()构造函数来创建一个新对象.当然,我也可以用等于r1的方式来做到这一点:

The intention was to create a new object by calling func() constructor. Sure, I can do it also this way which is equal to r1:

var r3 = require('./file');
var r4 = new r3.func('r1');

但是,我不明白为什么r2的行为方式与r1不同.

However, I do not understand why r2 does not behave the same way as r1.

require('./file')周围的多余括号如何产生作用?

How do the extra parenthesis around require('./file') make a difference?

推荐答案

这两个版本根本不同.

这个:

new (require('./file')).func('r1');

执行require,返回./file的导出,然后对结果调用新的运算符 .

Executes the require, returning the exports of ./file and then calling the new operator on the results .

这个:

var r2 = new require('./file').func('r2');

调用需要作为构造函数.

Invokes require as a constructor.

让我们看一个更孤立和简单的示例:

Let's look at a more isolated and simple example:

new Date() // creates a new date object
new (Date()) // throws a TypeError: string is not a function

这篇关于要求如何与Node.js中的新运算符一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆