簡體   English   中英

console.log 中的 JavaScript 對象輸出

[英]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.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"} ,這讓我懷疑如果我想與以這種方式構造的實例進行比較或繼承,我是否會在以后遇到問題.

更改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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM