Why does prototyping Function not affect console.log?

 ̄綄美尐妖づ 提交于 2019-12-01 17:04:52

问题


I prototyped Function so that it has a getBody function:

Function.prototype.getBody = function() {
    // Get content between first { and last }
    var m = this.toString().match(/\{([\s\S]*)\}/m)[1];
    // Strip comments
    return m.replace(/^\s*\/\/.*$/mg,'');
};

See here for more info. I tried to test it this way:

console.log(console.log.getBody.getBody());

but received an error: TypeError: console.log.getBody is undefined. I figured out that maybe this happens because console.log was defined before I actually prototyped Function so I created an empty function x right before the prototyping and tried to call

console.log(x.getBody.getBody());

which worked without a problem. Checking the type of console.log with typeof console.log results in "function". Here's a CodePen to try it out. All of this wasn't really a surprise since it's what I expected except of console.log.getBody to be undefined.

So why does prototyping Function not affect console.log? I'm using Firefox 18.0.1 with Firebug 1.11.1.


回答1:


This seems to be an issue with Firebug not with Firefox per se. My guess is that Function in Firebug lives in a different scope then Function in your page. (since unlike the other browsers Firebug is an extension , not a built in browser tool)

In fact if instead of Firebug you use the built in Firefox console (Ctrl+Shift+K), your code works perfectly fine.

More information about Firebug internals can be found here

http://getfirebug.com/wiki/index.php/Firebug_Internals

This excerpt may be interesting

When Firebug is detached from Firefox, open in a new or separate window, the new window has its own scope. In that scope, a few Firebug script tags compile to create a connection back to the original browser.xul window. Most important, chrome.js is unique to each top level window, but the Firebug object used by the detached window is the object of the parent browser.xul.



来源:https://stackoverflow.com/questions/14715140/why-does-prototyping-function-not-affect-console-log

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!