为什么原型功能不会影响console.log? [英] Why does prototyping Function not affect console.log?
问题描述
我原型化 Function
,使它有一个getBody函数:
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());
但收到错误: TypeError:console.log.getBody is undefined
。
我发现这可能是因为 console.log
是在我实际原型化 Function
之前定义的在原型之前创建了一个空函数 x
并尝试调用
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());
这没有问题。使用 typeof console.log
检查 console.log
的类型会导致function。以下是 CodePen 试用版。所有这一切都不是一个惊喜,因为除了 console.log.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.
那么为什么原型 Function
不会影响 console.log
?我使用Firefox 18.0.1与Firebug 1.11.1。
So why does prototyping Function
not affect console.log
? I'm using Firefox 18.0.1 with Firebug 1.11.1.
推荐答案
这似乎是一个问题,Firebug不是与Firefox本身。我的猜测是, Function
在Firebug中的生活在不同的范围,然后功能
在您的页面。 (因为与其他浏览器不同Firebug是一个扩展,而不是内置的浏览器工具)
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)
事实上,如果代替Firebug,你使用内置的Firefox控制台=https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Opening_the_Web_Console =nofollow> Ctrl + Shift + K ),您的代码工作得很好。
In fact if instead of Firebug you use the built in Firefox console (Ctrl+Shift+K), your code works perfectly fine.
有关Firebug内部结构的详细信息,请点击这里
More information about Firebug internals can be found here
http://getfirebug.com/wiki/index.php/Firebug_Internals
此摘录可能有趣
当Firebug与Firefox分离时,在新的或单独的
窗口中打开,新窗口有自己的范围。在那个范围内,一些Firebug
脚本标签编译创建一个连接回原来的
browser.xul窗口。最重要的是,chrome.js对每个top
级别窗口是唯一的,但是分离的窗口使用的Firebug对象是
父browser.xul的对象。
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.
这篇关于为什么原型功能不会影响console.log?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!