What `constructor` property is actually used?

In JavaScript, every function prototype object has an enumerable constructor property that points to a function ( EcmaScript ยง13.2 ). It is not used in any native functionality (for example, instanceof only checks the prototype chain), however, we recommend that you adjust it when overwriting the prototype property of the inherit function:

 SubClass.prototype = Object.create(SuperClass.prototype, { constructor: {value:SubClass, writable:true, configurable:true} }); 

But, do we (including me) do this only for clarity and accuracy? Are there any real use cases that rely on the constructor property?

+6
source share
2 answers

I cannot understand why the constructor property is what is in JS. Sometimes I find myself using it to get to prototype objects (for example, an Event object) in IE <9. However, I think this allows some programmers to manipulate the classic OO programming constructs:

 function Foo() { this.name = 'Foo'; } function Bar() { this.name = 'Bar'; } function Foobar(){}; Foo.prototype = new Foobar; Foo.prototype.constructor = Foo; Bar.prototype = new Foobar; Bar.prototype.constructor = Bar; var foo = new Foo(); var bar = new Bar(); //so far the set-up function pseudoOverload(obj) { if (!(obj instanceof Foobar)) { throw new Error 'I only take subclasses of Foobar'; } if (obj.constructor.name === 'Foo') { return new obj.constructor;//reference to constructor is quite handy } //do stuff with Bar instance } 

So, AFAIK, the "advantages" of a constructor property:

  • easy to instantiate objects from an instance
  • the ability to group your objects as subclasses of a particular class, but still be able to check what type of subclass you are dealing with.
  • As you say: be careful.
+2
source

What property of my constructor constructor is used to determine whether a particular object is created or constructed using any functional constructor.

This is a great example for this: http://www.klauskomenda.com/code/javascript-inheritance-by-example/

0
source

Source: https://habr.com/ru/post/926402/


All Articles