2016-04-05 7 views
1

Mein Code erstreckt, ist wie folgt:Javascript - Fehlerobjekt

function Example(){} 
Example.myMethod = function(){}; 
function SpecificExample(){} 
SpecificExample.prototype = Object.create(Example.prototype); 
SpecificExample.prototype.constructor = SpecificExample; 

Ich möchte SpecificExampleExample erstreckt. Warum funktioniert dieser Code nicht?

+2

'Example.myMethod = function() {};' ist eine Funktion zum Konstruktor angebracht, kein Prototyp Methode verwenden 'Beispiel. prototype.myMethod = function() {}; ' – somethinghere

Antwort

2

Example.myMethod ist eine Funktion, die an die Konstruktorfunktion/das Objekt angehängt ist, aber nicht Teil des Prototyps. Dies könnte eine statische Funktion genannt werden (und in ES6 ist es genau das). Um sie zu einem Teil Ihres Prototyps zu machen, fügen Sie sie zum Prototyp selbst:

function Example(){} 
Example.prototype.myMethod = function(){}; 
function SpecificExample(){} 
SpecificExample.prototype = Object.create(Example.prototype); 
// As @JaredSmith said, you shouldn't change the constructor, and why would you? 
// function SpecificExample(){} IS your constructor. So... 
// SpecificExample.prototype.constructor = SpecificExample; 
// should simply be removed. 
+0

Nun, technisch * kannst * du es, aber du solltest wirklich nicht .... –

+0

@JaredSmith Yeah technisch ist eine Menge Zeug möglich, aber ja, du bist richtig, besser sei richtig. Lass mich das ändern. – somethinghere

+0

Vielen Dank, ich weiß, es ist wie eine statische Methode (ich brauche es), das Problem war, dass ich den Konstruktor nicht ändern kann. @JaredSmith gibt es so etwas wie Leistungsprobleme? – Joy

Verwandte Themen