Closed Bug 599719 Opened 15 years ago Closed 15 years ago

Objects created from functions with reassigned prototype will have Object as constructor, not the function

Categories

(Core :: JavaScript Engine, defect)

x86
Windows 7
defect
Not set
normal

Tracking

()

RESOLVED INVALID

People

(Reporter: andre.selmanagic+mozilla, Unassigned)

Details

User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10 Build Identifier: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0b6) Gecko/20100101 Firefox/4.0b6 Assigning a new prototype-object to a function instead of adding members to the existing prototype will result in newly created objects having the wrong constructor. Given the following code: ----- BEGIN ----- function TestClass() { this.foo = "bar"; } TestClass.prototype = { testfunc: function testfunc() { } } var test = new TestClass(); ----- END ----- test.constructor will be: function Object() { [native code] } Having this code: ----- BEGIN ----- function TestClass() { this.foo = "bar"; } TestClass.prototype.testfunc = function testfunc() { }; var test = new TestClass(); ----- END ----- test.constructor will be: function TestClass() { this.foo = "bar"; } ... which is the correct constructor function. Checked this in Firefox 3.6 and 4.0b6 Reproducible: Always
Actually this is correct behaviour. I will try to explain. TestClass.prototype = {/* ... */} Will asign a new object to prototype. And the constructor of objects is the Object Function. So TestClass.prototype.constructor points to ({}).constructor, wich is function Object () { }. If you know cal new TestClass, it will just return the prototype property. And 'constructor' will be the constructor of the object you assigned to 'prototype'. In the other case, you dont change the TestClass.prototype.constructor property, wich is automaticly assigned when creating a new function. So to fix this, either use: TestClass.prototype.a = function () {}; Or: TestClass.prototype = { constructor: TestClass, a: function () {} }
Thanks for the explanation. Makes perfect sense. I always thought the constructor is set as a part of the "new"-operation. Didn't know it was part of the prototype-magic ... Marking it as RESOLVED INVALID now. Thanks! :)
Status: UNCONFIRMED → RESOLVED
Closed: 15 years ago
Resolution: --- → INVALID
You need to log in before you can comment on or make changes to this bug.