使用JS函数来使用另一个函数的语法?node.js

Using a JS function to use the syntax of another? node.js

本文关键字:函数 语法 node js JS 使用 另一个      更新时间:2023-09-26

这篇文章的标题可能不好,我们会尝试更好地解释。

基本上,我一直在尝试制作一个函数:

var readlineSync = require('readline-sync');
function i(context) {
  readlineSync.question(context)
} 
var Username = i("Testing the prompt: ") 
console.log(Username)  

我发现一遍又一遍地写readlineSync.question相当烦人,但运行代码会返回以下内容:

Testing the prompt: Hello
undefined

我做错什么了吗?

您不会从函数中返回任何内容。

应该是:

function i(context) {
  return readlineSync.question(context)
} 

您可以执行以下操作:

var i = readlineSync.question
// usage
i('Testing the prompt: ')

创建函数的别名

或者,如果您使用的是支持ES6的环境(Node 6或Chrome):

import { question as i } from 'readline-sync'
// usage
i('Testing the prompt: ')

与相同

var i = require('readline-sync').question
// usage
i('Testing the prompt: ')

您忘记了返回语句

function i(context){
 return readlineSync.question(context)
}