簡體   English   中英

Chrome和Firefox如何在控制台中打印對象的類名?

[英]How do Chrome and Firefox print the object's class name in the console?

如果我使用“傳統”Javascript類創建Foo類,則在控制台上打印Foo實例時,chrome和Firefox都會顯示Foo名稱:

function Foo(){
    this.x = 10;
}

console.log(new Foo());
// Foo {x: 10}

另一方面,如果我使用手動滾動原型繼承,那么在調試時我沒有得到有用的名稱

function mkClass(init, proto){
    return function(/**/){
         var obj = Object.create(proto);
         init.apply(obj, arguments);
         return obj;
    }
}

var Bar = mkClass(function(){ this.x = 10 }, {});

console.log(Bar());
// Object {x: 10}

有沒有辦法讓我的原型系統創建的類在控制台上打印時顯示其名稱? 到目前為止,我能想到的唯一方法是一個丑陋的黑客濫用eval為mkClass返回的當前匿名構造函數賦予不同的名稱。

似乎FF和chrome只是打印構造函數屬性 嘗試將其設置為有意義的內容,您應該看到結果。

function mkClass(init, proto){
    proto.constructor = {name: "Foo"};
    return function(/**/){
         var obj = Object.create(proto);
         init.apply(obj, arguments);
         return obj;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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