为什么 console.log 在 JSC 环境中不工作,但它在 Safari 的调试控制台中工作

Why doesn't console.log work in the JSC environment but it works in Safari's debug console

当我使用系统库中提供的 JSC (JavaScriptCore) 引擎时,它的行为与使用 Safari 的调试控制台时不同

$ /System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc
>>> console.log("hello");
Exception: TypeError: undefined is not an object (evaluating 'console.log')

console.log("hello"); 在 Safari 中完美运行时。

JSC 中不存在控制台对象 -- 如果您愿意,可以添加它 JavaScriptCore console.log

TL;DR

var Console = function () {
    this.log = function(msg){ debug(msg) }; 
};
var console = new Console();
console.log("hello");

Safari 创建一个在调试控制台中可用但在 JSC 环境中不可用的控制台对象。请参阅 Safari 的控制台文档 here

添加我自己的包装 JSC 调试方法的控制台对象解决了我的问题:

$ /System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc
>>> var Console = function () {
...     this.log = function(msg){ debug(msg) };
... };
undefined
>>> var console = new Console();
undefined
>>> console.log("hello");
-> hello
undefined

我最终得到了这个可以在其他 JS 引擎上工作并兼容 JSC 的衬里:

console = console || { log: (...args) => debug(Array.prototype.slice.call(args).join(' ')) }

我从上面的答案中学到了东西。

不过,由于我没有看到目标,我推测是为了查看 stdout 上的输出:

print('string')

准备就绪后,使用流编辑器将 'print' 替换为 'console.log'。