javascript - 在 Node 模块 module.exports 中使用胖箭头

标签 javascript node.js ecmascript-6

我是 Node 模块的新手。我试过了

module.exports = function (firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.fullName = function () { 
        return this.firstName + ' ' + this.lastName;
    }
}

然后

让 person1 = new person('Rajesh','Dhoundiyal')

这有效。但是当我尝试在 module.exports 中使用 Fat arrow 时,它不起作用。

例如module.exports = (firstName, lastName) => {

稍后会出现错误 person is not a constructor 。我不知道为什么会发生这种情况。谁能告诉我为什么胖箭头在这里不起作用。

最佳答案

thisarrow-funciton与其他正常功能不一样。 thisarrow-funciton指向 arrow-funciton上下文被定义,所以它不能用作构造函数 请引用Arrow functions :

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target.These function expressions are best suited for non-method functions, and they cannot be used as constructors.

关于javascript - 在 Node 模块 module.exports 中使用胖箭头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46700146/

相关文章:

JavaScript - 如何检查事件是否已添加

Javascript 使用装饰器将类变量转换为 Getter/Setter

node.js - git 添加 .添加node_modules时命令无响应

javascript - React : When not bound, 'this' 为 null,而不是 React 组件事件处理程序中未定义

javascript - 如何使用 React 子元素创建 <Modal.Title> 等元素

javascript - 如何在 html canvas 中用颜色填充一定比例的圆圈区域?

javascript - 下载文件后执行某些操作

JavaScript - 有没有办法通过指定的键属性合并 2 个对象?

node.js - Nodejs/Express/Cookies : how do you set signed cookies with a secret

javascript - Lodash 迭代嵌套循环