Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>constructor</code> is a regular property of the prototype object (with the <code>DontEnum</code> flag set so it doesn't show up in <code>for..in</code> loops). If you replace the prototype object, the <code>constructor</code> property will be replaced as well - see <a href="http://joost.zeekat.nl/constructors-considered-mildly-confusing.html" rel="noreferrer">this explanation</a> for further details.</p> <p>You can work around the issue by manually setting <code>Obj2.prototype.constructor = Obj2</code>, but this way, the <code>DontEnum</code> flag won't be set.</p> <p>Because of these issues, it isn't a good idea to rely on <code>constructor</code> for type checking: use <code>instanceof</code> or <code>isPrototypeOf()</code> instead.</p> <hr> <p>Andrey Fedorov raised the question why <code>new</code> doesn't assign the <code>constructor</code> property to the instance object instead. I guess the reason for this is along the following lines:</p> <p>All objects created from the same constructor function share the constructor property, and shared properties reside in the prototype.</p> <p>The real problem is that JavaScript has no built-in support for inheritance hierarchies. There are several ways around the issue (yours is one of these), another one more 'in the spirit' of JavaScript would be the following:</p> <pre><code>function addOwnProperties(obj /*, ...*/) { for(var i = 1; i &lt; arguments.length; ++i) { var current = arguments[i]; for(var prop in current) { if(current.hasOwnProperty(prop)) obj[prop] = current[prop]; } } } function Obj1(arg1) { this.prop1 = arg1 || 1; } Obj1.prototype.method1 = function() {}; function Obj2(arg1, arg2) { Obj1.call(this, arg1); this.test2 = arg2 || 2; } addOwnProperties(Obj2.prototype, Obj1.prototype); Obj2.prototype.method2 = function() {}; </code></pre> <p>This makes multiple-inheritance trivial as well.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload