console.log中的JavaScript对象输出

时间:2014-02-05 22:44:24

标签: javascript class new-operator 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.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属性后,它会在比较或继承期间爬行吗?

更新

最初的目的是做到以下几点。

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"}的结果打印,这让我怀疑如果我想在以后构建的实例进行比较或继承,我是否会遇到问题这样一来。

5 个答案:

答案 0 :(得分:3)

更改F.prototype会替换F的内容,而不是名称。旧的原型对象仍然存在,并且对它的引用内部存储在旧F的每个实例中。您可以通过致电f.__proto__´(已弃用)或Object.getPrototypeOf(f)来进行检查。

请注意__proto__是一个访问者proterty(内部是getter,而不是不动产),因此无法更改。

答案 1 :(得分:1)

这并不难,因为f最后是F的一个实例,范围解析的顺序(这个,原型,......)很明显: - )

例如,您可以运行此代码,您将看到在这种情况下它将打印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

答案 2 :(得分:0)

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

function A () { something: 123 }
new A();
console.log result: A {}
new B();
console.log result: ReferenceError: B is not defined

答案 3 :(得分:0)

object.constructor.name是另一种获取对象构造函数名称的方法。

答案 4 :(得分:0)

我是否可以为初衷提出另一种方法?只使用对原型对象的不同引用而不是原始对象没有rpoblem,所以你可以做到

function construct(constructor, args, context) { //lowercase, as it's a function, not a class
    return new constructor(args);
}

这应该首先创建正确的对象,不需要交换任何原型。

相关问题