0

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?

Community
  • 1
  • 1
Deets McGeets
  • 6,108
  • 7
  • 29
  • 38

2 Answers2

1

if you insist-

LessonProvider.prototype = new ContentProvider()
LessonProvider.prototype.constructor=LessonProvider;
kennebec
  • 102,654
  • 32
  • 106
  • 127
1

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);
Paul
  • 12,392
  • 4
  • 48
  • 58