![](/img/trans.png)
[英]Chrome Javascript Console - Reference to object output with console.log(obj)?
[英]JavaScript object output in console.log
我想知道在打印对象时console.log从哪里获取构造函数的名称。 此外,这实际上会影响任何代码明智吗?
function F() {
this.test = 'ok';
}
var f = new F();
console.log( f );
console.log(在 Chrome 中)的输出是: F {test: "ok"}
console.log 在哪里获得F
中的F {test...
?
如果我将F.constructor
、 F.prototype
和f.constructor
为随机内容,它仍会打印原始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
属性之后,它会在比较或继承过程中爬升吗?
更新
最初的目的是做以下事情。
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"}
,这让我怀疑如果我想与以这种方式构造的实例进行比较或继承,我是否会在以后遇到问题.
更改F.prototype
替换F
的内容,而不是名称。 旧原型对象仍然存在,对它的引用存储在旧F
每个实例内部。 您可以通过调用f.__proto__
´ (已弃用)或Object.getPrototypeOf(f)
检查它。
请注意__proto__
是一个访问器属性(内部是一个 getter,而不是一个真正的属性),所以它不能被改变。
这并不难,因为 f 最终是 F 的一个实例,并且范围解析的顺序(this、prototype、...)很明显:-)
例如,您可以运行此代码,您将看到在这种情况下它将打印 G:
function G() {
this.fail = 'bad';
}
function F() {
this.test = 'ok';
}
F.prototype = G;
F.constructor = G;
var f = new F(); // Prints F
console.log(f);
f.prototype = G; // Redefining f type info
f.constructor = G;
console.log(f); // Prints G
您创建了 F 的新实例,因此浏览器会打印该实例以帮助您跟踪日志记录。 即使您更改了原型,您仍然必须创建一个新的“F”才能获取对象。
function A () { something: 123 }
new A();
console.log result: A {}
new B();
console.log result: ReferenceError: B is not defined
object.constructor.name
是另一种获取对象构造函数名称的方法。
我可以建议另一种方法来实现初衷吗? 仅使用对原型对象的不同引用而不是原始引用是没有问题的,因此您可以这样做
function construct(constructor, args, context) { //lowercase, as it's a function, not a class
return new constructor(args);
}
这应该首先创建正确的对象,无需交换任何原型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.