2015-01-09 50 views
2

規範中是否有任何內容爲類定義了toString()方法?JavaScript的類:toString()方法

例如,假設我定義這個類:

class Foo { 
    constructor() { 
    console.log('hello'); 
    } 
} 

如果我叫Foo.toString(),我不知道我是否會得到:

class Foo { 
    constructor() { 
    console.log('hello'); 
    } 
} 

也許構造函數,匿名:

function() { 
    console.log('hello'); 
} 

或者可能是構造函數,但它的名字是:

function Foo() { 
    console.log('hello'); 
} 

或者,也許只是類名:

Foo

+4

您是否嘗試過運行代碼? – chead23

+4

你有沒有試過閱讀規範? – Barmar

+0

我已閱讀規範(https://people.mozilla.org/~jorendorff/es6-draft.html#sec-class-definitions),但沒有關於它的內容。但是,也許我沒有完全閱讀(toString可能在別處定義?),或者類可能像它們的基礎構造函數一樣行事? 如果它不在規範中,運行代碼並不重要,因爲理論上我可以自己創建一個ES6運行時,它可以做任何事情,當我在類上調用toString()時,會感覺像什麼。 –

回答

3

其實在ES6 「下課」 僅僅是一個函數。因此,要了解toString如何表現所謂的「班級」,您必須查看toString() specification for function。它說:

字符串表示必須有一個FunctionDeclaration FunctionExpression,GeneratorDeclaration,GeneratorExpession,ClassDeclaration,ClassExpression,ArrowFunction,MethodDefinition,或根據對象的實際特性GeneratorMethod的語法。

因此,例如 '的toString()' 下一個類:

class Foo { 
    // some very important constructor 
    constructor() { 
     // body 
    } 

    /** 
    * Getting some name 
    */ 
    getName() { 
    } 
} 

toString()方法將返回字符串:

Foo.toString() === `class Foo { 
    // some very important constructor 
    constructor() { 
     // body 
    } 

    /** 
    * Getting some name 
    */ 
    getName() { 
    } 
}`; 

PS

  1. 講究我寫了字符串我n回覆引用``。我做了它來指定多行字符串。
  2. 另外spec說use and placement of white space, line terminators, and semicolons within the representation String is implementation-dependent。但是現在所有的JS實現都保持不變。
  3. 您可以在Chrome Canary中測試示例,該示例現在支持ES6類。
+0

我想知道爲什麼我沒有考慮在那裏看:... / –