Monkey-patching console.log in PhantomJS



我试图在PhantomJS中应用monkeypatching到console.log:

function doTheMonkey( ){
  console._log = console.log; //Typo, was console.log()
  console.log = function log( ){
      console._log.apply( this , arguments );    
      return arguments;
  }
}

PhantomJS会报错TypeError: Type error for
console._log.apply( this , arguments );

为了深入到最简单的失败示例,我可以提供以下内容:

function logAndReturn( ){
  console.log.apply( this , arguments );
  return arguments;
}
同样,使用TypeError也会失败:
console._log.apply( this , arguments ); 类型错误

这应该只是工作,我不知道根本原因是什么…

正如另一个答案所述,您应该做

console._log = console.log

那么当你将arguments应用于console._log时,你需要做

console._log.apply(console, Array.prototype.slice.call(arguments));

arguments值不是数组。使用slice,您可以创建一个。

您在第一行调用console.log而不是对函数进行引用,即

console._log = console.log();
应该

console._log = console.log;

最新更新