0

What I want to do is extract the name of a function in JavaScript. I got this working some time ago and it looks something like this:

MyObj = function myobj(){};

extend = function(obj){
    return /function (.+)\(/.exec(obj.constructor.toString())[1];
}

So here is the funny thing. When I use prototype with this object in this way, it all works fine:

MyObj.prototype.a = function(){}
MyObj.prototype.b = function(){}

extend(MyObj);
//->'myobj'

However, when I define my function like this:

MyObj.prototype = {
   a : function(){},
   b : function(){}
}

extend(MyObj);
//->'Object'

Does anybody has any idea why the constructor in the latter method is part of JavaScript's native code (e.g. 'Object'), instead of my function?

Any help would be greatly appreciated!

2 Answers 2

2

Try adding the constructor property in your second case.
Because you're overwriting the prototype, you're also overwriting the obj.prototype.constructor property.
So use it like this :

MyObj.prototype = {
    constructor : MyObj,
    method1 : ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

Because when you use "MyObj.prototype.a", you are using native prototype and adding a new function to it.

But when you use the other way, you are replacing the native prototype with a new Object.

Comments

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.