为什么原型设计功能不会影响console.log?

Yin*_*ang 6 javascript console prototyping

我原型,Function以便它有一个getBody函数:

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,'');
};
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参见此处 我试着用这种方式测试它:

console.log(console.log.getBody.getBody());
Run Code Online (Sandbox Code Playgroud)

但收到错误:TypeError: console.log.getBody is undefined.我发现可能发生这种情况是因为console.log在我实际制作原型之前定义了Function所以我在原型设计之前创建了一个空函数x并尝试调用

console.log(x.getBody.getBody());
Run Code Online (Sandbox Code Playgroud)

哪个没有问题.检查的类型console.log与typeof console.log在"功能"的结果.这是一个CodePen来试一试.所有这一切都不是一个惊喜,因为它是我所期望的,除了console.log.getBody未定义.

那么为什么原型设计Function不会影响console.log?我在Firebug 1.11.1中使用Firefox 18.0.1.

los*_*rce 5

这似乎是Firebug的一个问题,而不是Firefox本身.我的猜测是,FunctionFirebug Function在你的页面中生活在不同的范围内.(因为与其他浏览器不同,Firebug是一个扩展,而不是内置的浏览器工具)

事实上,如果您使用内置的Firefox控制台(Ctrl + Shift + K)而不是Firebug ,您的代码就可以正常运行.

有关Firebug内部的更多信息,请点击此处

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

这段摘录可能很有趣

当Firebug与Firefox分离时,在新的或单独的窗口中打开,新窗口有自己的范围.在该范围内,一些Firebug脚本标记进行编译以创建回到原始browser.xul窗口的连接.最重要的是,chrome.js对于每个顶级窗口都是唯一的,但是分离窗口使用的Firebug对象是父browser.xul的对象.

  • 问题出在Firebug,而不是Firefox.:) (2认同)