rcooper102
rcooper102

Reputation: 209

Getting the Parent Function that Created an Instance

So this is a somewhat weird problem that may not be possible but I was wondering if it is possible to get a variable linkage of the function that created an instance from javascript.

for example, i'd like to be able to do something like this:

function MyObject(){
    console.log(this) // traces out the instance
    console.log(MyObject) // traces out the function
    console.log(this.parentClass) //Would like this to trace out the function as well. (or a similar call like it)
}

var test = new MyObject();

Is this at all possible? Thanks!!

Upvotes: 0

Views: 24

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074545

It's possible if the prototype objects on the functions haven't been replaced, or if the code replacing them keeps the linkage as it is by default.

The constructor property is (by default and convention) the property you're looking for:

var test = new MyObject();
console.log(test.constructor === MyObject); // "true"

Note all of the caveats above, though. For instance, this is perfectly valid (and not particularly atypical) code:

function MyObject() {
}
MyObject.prototype = {
    foo: function() { /* ... */ },
    bar: function() { /* ... */ }
};

This is a common pattern, although one I don't recommend. Instead of adding to the object referred to by the MyObject.prototype property (an object that was set up by the JavaScript engine when creating MyObject), that code is creating an entirely new object and assigning it to the prototype property, making it refer to the new object. If that has been done, then the constructor property has been broken, and you can't use it the way you want to use it.

The constructor property on the default prototype object on functions is a funny thing about JavaScript. It's defined quite clearly in the specification that it will be there (it's §13.2 if anyone wants to read up), but as far as I'm aware nothing in the JavaScript engine actually uses it. (It isn't, for instance, used for instanceof.)

Upvotes: 1

Related Questions