简体   繁体   中英

Javascript constructor behaves different when defining prototype in two different ways

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 (eg '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 the obj.prototype.constructor property.
So use it like this :

MyObj.prototype = {
    constructor : MyObj,
    method1 : ...
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM