1

My code is like following:

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

I want SpecificExample extends Example. Why this code doesn't work?

1
  • 2
    Example.myMethod = function(){}; is a function attached to your constructor, not a prototype method, use Example.prototype.myMethod = function(){}; Commented Apr 5, 2016 at 15:26

1 Answer 1

2

Example.myMethod is a function attached to the constructor function/object, but it is not part of its prototype. This could be called a static function (and in ES6 it is exactly that). To make them part of your prototype, add them to the prototype itself:

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.
Sign up to request clarification or add additional context in comments.

6 Comments

@JaredSmith Yeah technically a lot of stuff is possible, but yeah, you're right, better be correct. Let me change that.
Thanks you a lot, I know it is like a static method (I need it), the problem was that I can't change the constructor. @JaredSmith there are something like performance problems?
More like unexpected behavior problems. Put a line Object.prototype = null; at the top of your script file as an example of why not to mess with built in stuff...
@Joy Actually, quick question: are you trying to make a sort of inheritable static method? Because I don't get why you want to change the constructor (certainly not since you are changing it to the same function that already is your constructor)...
Also why you'd want an inheritable static method, which would almost certainly be an xy problem...meta.stackexchange.com/questions/66377/what-is-the-xy-problem
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.