为什么 yargs.argv 导致处理函数调用
why yargs.argv causes handler function to invoke
const yargs = require("yargs");
yargs.version = "1.0.0";
yargs.command({
command: "add",
describe: "do addition ",
handler: function () {
console.log("addition complete");
},
}).argv;
在上面使用 yargs 的代码中,我试图创建一个命令 add
并在 运行 与 node . add
连接脚本时执行处理程序函数,我得到预期的输出
$ node . add
addition complete
但是当没有 .argv 的相同代码是 运行 时,输出为空白并且不执行处理函数。
在文档中没有说明 .argv 是什么,它是一个对象还是一个函数,以及它是如何工作的。乍一看,它看起来像一个普通的方法调用,但是
当您执行以下操作时
console.log(typeof yargs.argv);
输出为
$ node . add
addition complete
object
如果 yargs.argv 与任何其他对象一样,那么只要访问它,就可以调用它的方式和原因一个函数
有人可以解释一下到底发生了什么以及我错过了什么吗。
Yargs 使用 #getter
,这允许 javascript 在调用 属性 时调用函数。
示例:
const obj = {
log: ['a', 'b', 'c'],
get latest() {
if (this.log.length === 0) {
return undefined;
}
return this.log[this.log.length - 1];
}
};
console.log(obj.latest);
// expected output: "c"
如果你查看 source code 你可以看到当你调用 .argv
时,yargs 只调用 .parse()
:
const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim);
// Legacy yargs.argv interface, it's recommended that you use .parse().
Object.defineProperty(yargs, 'argv', {
get: () => {
return yargs.parse();
},
enumerable: true,
});
const yargs = require("yargs");
yargs.version = "1.0.0";
yargs.command({
command: "add",
describe: "do addition ",
handler: function () {
console.log("addition complete");
},
}).argv;
在上面使用 yargs 的代码中,我试图创建一个命令 add
并在 运行 与 node . add
连接脚本时执行处理程序函数,我得到预期的输出
$ node . add
addition complete
但是当没有 .argv 的相同代码是 运行 时,输出为空白并且不执行处理函数。 在文档中没有说明 .argv 是什么,它是一个对象还是一个函数,以及它是如何工作的。乍一看,它看起来像一个普通的方法调用,但是
当您执行以下操作时
console.log(typeof yargs.argv);
输出为
$ node . add
addition complete
object
如果 yargs.argv 与任何其他对象一样,那么只要访问它,就可以调用它的方式和原因一个函数
有人可以解释一下到底发生了什么以及我错过了什么吗。
Yargs 使用 #getter
,这允许 javascript 在调用 属性 时调用函数。
示例:
const obj = {
log: ['a', 'b', 'c'],
get latest() {
if (this.log.length === 0) {
return undefined;
}
return this.log[this.log.length - 1];
}
};
console.log(obj.latest);
// expected output: "c"
如果你查看 source code 你可以看到当你调用 .argv
时,yargs 只调用 .parse()
:
const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim);
// Legacy yargs.argv interface, it's recommended that you use .parse().
Object.defineProperty(yargs, 'argv', {
get: () => {
return yargs.parse();
},
enumerable: true,
});