console.log中的JavaScript对象输出 [英] JavaScript object output in console.log
问题描述
我想知道console.log在打印对象时从哪里获得构造函数的名称.而且,这实际上对代码有影响吗?
I want to know from where does console.log get the name of the constructing function when printing an object. Also, does that actually effect anything code wise?
function F() {
this.test = 'ok';
}
var f = new F();
console.log( f );
console.log的输出(在Chrome中)是:F {test:"ok"}
The output of console.log (in Chrome) is: F {test: "ok"}
console.log在哪里从 F {test ...
中获取 F
?
Where does the console.log get the F
in F {test...
?
如果我将 F.constructor
, F.prototype
和 f.constructor
更改为随机值,它仍会打印原始的 F
:
If I change F.constructor
, F.prototype
, and f.constructor
to something random, it still prints the original F
:
function G() {
this.fail = 'bad';
}
function F() {
this.test = 'ok';
}
F.prototype = G;
F.constructor = G;
var f = new F();
console.log( f );
输出仍然相同- F {test:"ok"}
此信息是否只是由浏览器私下保存,我的问题是,它是否以任何方式影响JavaScript代码?也就是说,在我重写构造函数的 prototype
和 constructor
属性之后,它会在比较或继承期间爬升吗?
Is this information is simply kept privately by the browser, my question is does it affect JavaScript code in any way? That is, will it creep up during comparison or inheritance, after I override the constructor's prototype
and constructor
properties?
更新
最初的目的是执行以下操作.
The original purpose was to do the following.
function Person ( _name ) {
this.name = _name;
}
function Construct( _constructor, _args, _context ) {
function F () {
var context = _context || this;
return _constructor.apply( context, _args );
}
/* I want to have the constructed object by identified
as _constructor and not a F */
F.prototype = _constructor.prototype;
return new F();
}
function Make ( _who ) {
if ( 'person' === _who ) {
/* Remove the first argument, who, and pass along all the rest.
Constructors cannot be called with .apply so I have to use
this technique. */
return Construct( Person, Array.prototype.slice.call( arguments, 1 ) );
}
}
var dev = Make( 'person', 'John Doe' );
console.log( dev ); // prints `F {name: "John Doe"}`
如您所见,生成的 dev
打印输出为 F {name:"John Doe"}
,这使我怀疑以后是否会遇到问题如果我想与以这种方式构造的实例进行比较或继承.
As you can see, the resulting print of dev
outputs F {name: "John Doe"}
, which made me question whether I may run into problems later on if I'd like to make comparisons or inheritance with instances constructed in such a way.
推荐答案
更改 F.prototype
会替换 F
的内容,而不是名称.旧的原型对象仍然存在,并且对它的引用存储在旧的 F
的每个实例的内部.您可以通过调用 f来对其进行检查.__proto __
´(不建议使用)或
Changing F.prototype
replaces the content of F
, not the name. The old prototype object still exists and a reference to it is stored internally in each instance of the old F
. You cam check it by calling f.__proto__
´ (deprecated) or Object.getPrototypeOf(f)
.
请注意, __ proto __
是访问者属性(内部是getter,而不是不动产),因此无法更改.
Note that __proto__
is an accessor proterty (internally a getter, not a real property), so it cannot be changed.
这篇关于console.log中的JavaScript对象输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!