简体   繁体   English

在node.js中更改名称后无法访问功能

[英]Can't access function after name changed in node.js

There is a function in one of my files in project which I changed it's name and can't access it with new name!项目中的一个文件中有一个函数,我更改了它的名称并且无法使用新名称访问它! still the old name is available to call仍然可以调用旧名称

I tried deleting node_modules and install it again using npm i我尝试删除 node_modules 并使用npm i重新安装它

there is the code to both files I'm using:我正在使用的两个文件都有代码:

soapCall.js肥皂调用.js

before:前:

function call(username, password){
    ...
}

module.exports = call

after:后:

function checkUser(username, password){
    ...
}

module.exports = checkUser

how I imported and used:我如何导入和使用:

app.js应用程序.js

const soap = require('../../models/soapCall');
...
soap.checkUser(username, password);

it's weired that still I can't access the new function name奇怪的是我仍然无法访问新的函数名称

I was using name call before that and STILL can use call function in my app.js file在此之前我使用了名称call ,并且仍然可以在我的 app.js 文件中使用call函数

call is already available as a method on the function prototype - Function.prototype.call . call已经作为函数原型上的一个方法可用 - Function.prototype.call This means soap is a function, which is why call works, but checkUser doesn't.这意味着soap是一个函数,这就是为什么call起作用,而checkUser不起作用。

soap is a function because you're exporting a function from your file, and simply renaming it in your main file. soap是一个函数,因为您从文件中导出一个函数,然后在主文件中简单地重命名它。 If you want to change the name, either change the import name:如果要更改名称,请更改导入名称:

const checkUser = require("../../models/soapCall");

Or export an object and use it as such:或者导出一个对象并像这样使用它:

module.exports = { checkUser };
// Main file
const soap = require("../../models/soapCall");
soap.checkUser(...);

The object method will also allow you to export multiple functions from the one file - you can get these into their own variables with destructuring: object 方法还允许您从一个文件中导出多个函数 - 您可以通过解构将这些函数放入它们自己的变量中:

module.exports = { checkUser, otherFunc };
// Main file
const { checkUser, otherFunc } = require("../../models/soapCall");
checkUser(...); // Calls checkUser function
otherFunc(...); // Calls otherFunc function

You are exporting a function not an Object, so you need to directly call soap() .您正在导出一个函数而不是一个对象,因此您需要直接调用soap()

And about being able to run call , it's part of function prototype.关于能够运行call ,它是函数原型的一部分。 So you got confused with Function.prototype.call()所以你对Function.prototype.call()感到困惑

Use it like this, as per the comment by @Wiktor Zychla根据@Wiktor Zychla 的评论,像这样使用它

soapCall.js肥皂调用.js

exports.checkUser(username, password){

}

app.js应用程序.js

const soap = require('../../models/soapCall');
soap.checkUser(username, password);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM