console.log中的JavaScript对象输出

问题描述 投票:7回答:5

我想知道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.constructorF.prototypef.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代码?也就是说,在我重写构造函数的prototypeconstructor属性之后,它会在比较或继承期间爬升吗?

UPDATE

最初的目的是执行以下操作。

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"},这使我感到怀疑,如果以后我想与以这种方式构造的实例进行比较或继承,是否会遇到问题。] >

我想知道console.log在打印对象时从何处获取构造函数的名称。另外,这实际上对代码有影响吗?函数F(){this.test ='ok'; ...

javascript class new-operator console.log
5个回答
3
投票

更改F.prototype将替换F的内容,而不是名称。旧的原型对象仍然存在,并且对它的引用存储在旧的F的每个实例中。您可以通过调用f.__proto__´(不建议使用)或f.__proto__来对其进行检查。


1
投票

这并不困难,因为f最终是F的一个实例,并且范围解析的顺序(this,prototype等)很明显:-)


0
投票

您正在创建F的新实例,因此浏览器会打印出来,以帮助您跟踪日志记录。即使您更改了原型,仍然必须创建一个新的“ F”以获取对象。


0
投票

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 是获取对象构造函数名称的另一种方法。


0
投票

我是否可以为初衷建议另一种方法?仅使用对原型对象的不同引用而不是原始对象是没有问题的,因此可以执行

© www.soinside.com 2019 - 2024. All rights reserved.