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!
Try adding the constructor property in your second case.
Because you’re overwriting the
prototype, you’re also overwriting theobj.prototype.constructorproperty.So use it like this :