我正在学习nodejs(而且我喜欢它!)。我试图弄清楚如何使用更短的别名console.log
我发现我可以使用var cout=console.log
并使用cout('[string]')
从那时起。然后当我想使用process.stdout.write
我也尝试为它创建一个简短的别名,使用var out=process.stdout.write
。但是当我使用out('[string]')
,我收到以下错误:
_stream_writable.js:220 var state = this._writableState;
^ 类型错误:无法读取未定义的属性“_writableState”
在 Writable.write (_stream_writable.js:220:19)
在 Socket.write (net.js:670:40)
在对象。 (/home/shayan/Desktop/nodejs/server.js:12:1)
在 Module._compile (module.js:571:32)
在 Object.Module._extensions..js (module.js:580:10)
在 Module.load (module.js:488:32)
在 tryModuleLoad (module.js:447:12)
在 Function.Module._load (module.js:439:3)
在 Module.runMain (module.js:605:10)
运行时(bootstrap_node.js:423:7)
这里有什么问题吗?
如何正确创建一个短别名process.stdout.write
?
Thanks
你不应该做这种“短别名”。它非常混乱,阅读你的代码的人不会理解为什么你使用随机函数名称而不是console.log
。但是,如果您确实想创建函数别名,请考虑使用function
:
function out(text) {
// ^ ^- argument accepted by the function
// |------ the function name
process.stdout.write(text)
// ^- pass the argument you accepted in your new function to the long function
}
我添加了一些解释,以防您不知道某个函数是如何工作的,您可以安全地删除它。
Edit:它不起作用的原因在于 Node.JS 的源代码。您返回的堆栈跟踪指向this https://github.com/nodejs/node/blob/master/lib/_stream_writable.js#L236 line:
Writable.prototype.write = function(chunk, encoding, cb) {
var state = this._writableState;
// ...
}
它尝试引用一个名为的变量_writableState
from this
。如所写here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#Function_context:
在函数内部,值this
取决于函数的调用方式。
这意味着this
指的是process.stdout
你打电话时process.stdout.write
,但是当您从别名调用它时,它是未定义的。因此你得到一个Cannot read property '_writableState' of undefined
例外(如undefined
不包含该变量,这对于write
执行的函数)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)