最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

When I use the JSC (JavaScriptCore) engine provided in the System Library, it acts differently then when using Safari's debug console

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

When console.log("hello"); works perfectly fine in Safari.

When I use the JSC (JavaScriptCore) engine provided in the System Library, it acts differently then when using Safari's debug console

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

When console.log("hello"); works perfectly fine in Safari.

Share Improve this question edited Jan 21, 2016 at 18:26 sdc asked Jan 21, 2016 at 2:31 sdcsdc 3,0411 gold badge31 silver badges44 bronze badges 5
  • 1 Because there's no console object in JSC, apparently. – Barmar Commented Jan 21, 2016 at 2:37
  • @Barmar can you convert this to an answer so I can accept it? - Thanks – sdc Commented Jan 21, 2016 at 2:45
  • I don't know anything about JSC, I just based that on the symptom. What's wrong with John Hascall's answer, that explains how to solve it? – Barmar Commented Jan 21, 2016 at 2:47
  • @Barmar the problem has nothing to do with an Objective C or C environment but a JSC environment – sdc Commented Jan 21, 2016 at 3:04
  • OK, I've reopened the question. You should put your solution in an answer, not the question. – Barmar Commented Jan 21, 2016 at 3:20
Add a ment  | 

4 Answers 4

Reset to default 7

TL;DR

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

Safari creates a console object that is available in the debug console, but not in the JSC environment. See Safari's console documentation here

Adding my own console object that wraps the JSC debug method solved my problem:

$ /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

The console object doesn't exist in JSC -- you can add it if you like JavaScriptCore console.log

I've ended up with this one liner that works on other JS engines along with JSC patibility:

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

I learned from the answers above.

Though, as I not see a goal, I presume it was to see output on stdout:

print('string')

And when ready, use a stream editor to substitute 'print' with 'console.log'.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论