2017-12-11 8 views
1

Ich möchte die getArea() Funktion ein Prototyp machen, und bin mir nicht sicher, ob dieses ES6 (?) Format automatisch dies für mich tut, oder muss ich noch einen Prototyp in einem separaten Object.prototype.method = function() {} deklarieren bauen?JavaScript ES6 Prototyp Funktion

class Polygon { 
    constructor(height, width) { 
     this.height = height; 
     this.width = width; 
    } 
    getArea() { 
     return this.height * this.width; 
    } 
} 
+0

[Siehe die Bestätigung selbst] (https://babeljs.io/repl/#?babili=false&browsers=&build=&builtIns=false&code_lz = MYGwhgzhAEAKD2ICeBzeA7aBvAUNf0wGEALgE4CuwJ8ZAFABYCmAligyQDTQDuLAJiQYBKbHgIShLCADpmbDtAC80eexIBucRPxTZfQQ2W8BQrRIC-26CiYkAgmSZg6o3DoJOSFMpj1zWdWgAKmh_AzNrKwsgA & debug = false & circleciRepo = & bewerten = true & lineWrap = false & Presets = es2015-lose & hübschere = false & Ziele = & version = 6.26.0) –

+0

gibt es einen Grund, warum Sie würde sich nicht nur überprüfen? 'console.log (Polygon.prototype.getarea)' –

Antwort

4

Es ist.

Das ES6 Klasse-Format übersetzt im Grunde so etwas wie folgt aus:

function Polygon(height, width) { 
    this.height = height; 
    this.width = width; 
} 

Polygon.prototype.getArea = function() { 
    return this.height * this.width; 
}; 
+0

Weitere Bestätigung - Ich habe gerade den Code aus der Frage mit TypeScript und Babel kompiliert und das ist ziemlich genau der Code, der ausgegeben wird. –

+0

Eine wichtige Unterscheidung wäre, dass die Methode nicht aufzählbar wäre. –

+0

Ich bin mir nicht sicher, wie ES6 oder ES5 Syntax in dieser Hinsicht wirklich abweichen würde. – samanime