5

Yes, I've seen this asked and answered before. But here's what I still don't understand:

If I create a constructor function, and don't override the function's prototype property, then we have the automatic constructor property hanging off the function's prototype property. That is MyConstructor.prototype.constructor === MyConstructor => true. Great. But now what happens when I override prototype with my own object, and don't patch up the constructor property? constructor now doesn't exist on prototype, and if referenced is only found up the prototype chain, that is MyConstructor.prototype.constructor === Object => true. Fine. So...

Why is it that in a Javascript debugger (like Chrome), if I override a constructor's prototype with my own object, and new up an instance of that constructor, and then type that instance variable on the command line, Chrome happily tells me the type? How does it know??? I.e. what can I do to find out the same thing through code?

Simple repro:

> function Foo() {}
undefined
> Foo.prototype.constructor === Foo
true
> Foo.prototype = {}
Object
> Foo.prototype.constructor === Foo
false
> f = new Foo()
Foo
> f
Foo

Is it pure debugger magic?

curtc
  • 263
  • 1
  • 3
  • 7
  • The association is still there somewhere - since `f instanceof Foo` returns `true` - but I don't think it's exposed to user code. Whcih I guess makes it pure debugger magic. – Mark Reed May 05 '12 at 05:16
  • 1
    This one seems related – g13n May 05 '12 at 05:25
  • firefox seems to lack the debugger magic since the f = new Foo() and f lines both return [object Object] which the linked answer above explains – nvuono May 05 '12 at 05:27
  • Yes @g13n, that link is related, but only talks about the part that I understand, it does not answer the question. I didn't realize Firefox doesn't display Foo. I will assume that it is in fact debugger magic, and not possible through user code, without manually storing additional data. Thx. – curtc May 05 '12 at 14:23
  • @curtc yep AFAIK it is not possible through userland code. Newer versions of Firefox has a JavaScript console (triggerred through Ctrl+Shift+K) on Windows, GNU/Linux. Both this console and Firebug just knows that they're objects and nothing beyond that. – g13n May 05 '12 at 20:13

1 Answers1

0

Maybe the solution is simply to not set the prototype to your custom object? You could loop over all of the properties of your custom object, and add them as properties to the existing prototype, therefore retaining all of the properties of the original prototype object, such as the constructor.

JKing
  • 807
  • 5
  • 14
  • That, or add a property to your custom prototype object that holds a reference to the constructor function, or even simply some custom string or something that you can check... – JKing May 11 '12 at 22:04