简体   繁体   English

为什么`window.console.log(this)`不记录控制台对象?

[英]Why does `window.console.log(this)` not log the console object?

I'm just getting into advanced contextual instantiation, using prototype chain etc. 我只是进入高级上下文实例化,使用原型链等。

I'm curious how the window.console object is created such that the function log thinks it's context is the window instance, not the console. 我很好奇如何创建window.console对象,以便函数log认为其上下文是窗口实例,而不是控制台。 Is this something to do with Object.create the new keyword, or binding / self = this? 这与Object.create new关键字有关,还是绑定/ self = this?

window.console has a constructor (Console) and I'm curious what the cleanest way to invoke the constructor, passing Window instance/context would be? window.console有一个构造函数(Console),我很好奇,通过Window实例/上下文调用构造函数的最简单方法是什么? Pass it in as a param?? 作为参数传递它? If Console is a seperate constructor, I think Window would be the one constructing it with a new context, rather than saying 如果Console是一个单独的构造函数,我认为Window将是使用新上下文构造它的那个,而不是说

windowInstance.console.log = function (args) {

}.bind(windowInstance, args);

Pretty much, I'm imagining a layout like this, but don't understand how this gets routed 好看多了,比我想象这样的布局,但不明白怎么this被路由

var window = new Window();
window.console.log(this); // logs window

function Window () {
    // this === window when constructed above
    this.console = new Console();
}

function Console () {
    this.log = function () {} // where this === window.console but log thinks it's window
}

Thanks 谢谢

If you had: 如果你有:

var obj = { hello: "world" };
console.log(obj);

would you be surprised that the console showed that object? 您会为控制台显示该对象感到惊讶吗? Well by the same token, 同样,

console.log(this);

logs the value of this as it is outside the call to the console function. 记录的值this ,因为它是调用控制台功能之外 You can't force console.log() to log what it thinks the value of this is in its own frame of reference; 你不能强迫console.log()来记录它认为的价值this是在自己的参照系; there's just no provision for that in the API (because frankly it's not very useful). API中对此没有任何规定(坦率地说,它不是很有用)。 If you want to log the state of the window.console object however you can: 但是,如果要记录window.console对象的状态,则可以:

console.log(window.console);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM