jscript函数指针
在 MS JScript 中,我可以编写
WSH.Echo("hello world");
并通过命令行 cscript.exe 运行它,它按预期工作。
但是如果我想使用函数 print() 进行打印,一种解决方案是将目标函数分配给一个名为 print 的变量,就像这样,它适用于大多数 JS 解释器,
var print=WSH.Echo
print("hello world");
但这不适用于 cscript.exe 并打印以下错误消息是
Microsoft JScript runtime error: Object doesn't support this property or method
我做错了什么吗?是否有任何快捷方式可以实现它,而无需为我要重命名的每个函数编写单独的包装函数?
In MS JScript I can write
WSH.Echo("hello world");
And run it through command line cscript.exe which works as expected.
But if I want to use the function print() for printing, one solution is to assign the target function to a variable called print, like this, which works with most JS interpreter
var print=WSH.Echo
print("hello world");
But that doesn't work with cscript.exe and prints the following error message
Microsoft JScript runtime error: Object doesn't support this property or method
Am I doing something wrong? Is there any shortcut way to achieve it without writing individual wrapper function for each function that I want to rename?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
被调用函数的上下文正在发生变化。如果
Echo
函数包含对this
的相对引用,您需要在 WSH 对象的上下文中调用该函数。一个简单的解决方案是仅使用包装函数:现在,当然,重复执行很糟糕,因此您需要制作一个包装生成器:
这只是一个简单的示例,您应该能够使用
调用
和apply
以便返回的函数采用参数数量可变。The context of the function being called is changing. If the
Echo
function contains a relative reference tothis
, you'll need to call the function in the context of the WSH object. A simple solution is to just use a wrapper function:Now, of course that sucks for doing repetitively, so you'll want to make a wrapper generator:
This is just a simple example, you should be able to easily extend this using
call
andapply
so that the returned function takes a variable number of arguments.