开发者

jscript function pointer

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 开发者_StackOverflow中文版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?


The context of the function being called is changing. If the Echo function contains a relative reference to this, you'll need to call the function in the context of the WSH object. A simple solution is to just use a wrapper function:

var print = function (param)
{
  WSH.Echo(param);
};

Now, of course that sucks for doing repetitively, so you'll want to make a wrapper generator:

function alias(fn, context)
{
  return function(param)
  {
    context[fn](param);
  };
}

var print = alias('Echo', WSQ);

This is just a simple example, you should be able to easily extend this using call and apply so that the returned function takes a variable number of arguments.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜