javascript - 为什么 prototyping Function 不影响 console.log?

标签 javascript console prototyping

我制作了 Function 原型(prototype),使其具有 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,'');
};

参见 here获取更多信息。 我试过这样测试:

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

但收到错误:TypeError: console.log.getBody is undefined。 我发现这可能是因为 console.log 是在我实际制作原型(prototype) Function 之前定义的,所以我在制作原型(prototype)之前创建了一个空函数 x并试图调用

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

这没有问题。使用 typeof console.log 检查 console.log 的类型导致“功能”。这是一个 CodePen尝试一下。所有这些都不是真正的惊喜,因为除了 console.log.getBody 是未定义的之外,这是我所期望的。

那么,为什么原型(prototype)设计 Function 不会影响 console.log?我正在使用 Firefox 18.0.1 和 Firebug 1.11.1。

最佳答案

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

事实上,如果您使用内置的 Firefox 控制台 ( Ctrl+Shift+K ) 而不是 Firebug,您的代码将运行得非常好。

可以在此处找到有关 Firebug 内部结构的更多信息

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

这段摘录可能很有趣

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.

关于javascript - 为什么 prototyping Function 不影响 console.log?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14715140/

相关文章:

javascript - Axios请求在iOS上显示响应,但不适用于android

javascript - 如何将方法放到 Redux 状态的对象上?

javascript - console.log() 和 console.debug() 的区别?

javascript - 原型(prototype)制作的任何其他想法

javascript - 正则表达式只有 8 个字符长,但不超过 2 个数字

javascript - 如何在使用 $.merge() 时保留 jQuery 元素数据值

c# - 模拟 'System.Console' 行为

java - Solaris 上的字符集

prototyping - 原型(prototype)设计时的最佳实践?

user-interface - 快速制作 GUI 原型(prototype)