Search code examples
javascriptoopprototype-programming

Getting the type of an object in Javascript when its prototype is assigned an instance of another object


I must have some sort of fundamental misunderstanding of how objects work in Javascript because I am unable to figure out why the following outputs what it does. You can see the jsfiddle of the following code here: http://jsfiddle.net/VivekVish/8Qvkn/1/

Note that is uses the getName function defined here: How do I get the name of an object's type in JavaScript?

Object.prototype.getName = function()
{ 
   var funcNameRegex = /function (.{1,})\(/;
   var results = (funcNameRegex).exec((this).constructor.toString());
   return (results && results.length > 1) ? results[1] : "";
};

function ContentProvider()
{

}

function LessonProvider()
{
    console.log(this.getName());
}

lessonProvider1 = new LessonProvider();
LessonProvider.prototype = new ContentProvider();
lessonProvider2 = new LessonProvider();

The above code outputs the following to the console:

LessonProvider

ContentProvider

But why isn't it LessonProvider in both cases and how can one make it LessonProvider in both cases?


Solution

  • If you don't reset the pointer to the constructor, the all the children will report that the parent object is their constructor.

    LessonProvider.prototype.constructor = LessonProvider;
    

    You may want to try using a function like below for inheritance:

    function inherit(C, P) {
        //empty function used as a proxy
        var F = function() {};
        //set F's prototype equal to P's prototype
        F.prototype = P.prototype;
        //C will only inherit properties from the F's prototype
        C.prototype = new F();
        //set access to the parents (P's) prototype if needed
        C.uber = P.prototype;
        //Set the constructor back to C
        C.prototype.constructor = C;
    }
    
    inherit(LessonProvider, ContentProvider);