Object.defineProperty(Class.prototype, 'constructor', ... vs Class.prototype.constructor = Class

In the Inheritance article for JavaScript Objects module, the instructions and example code advise to use the following snippet to update the Teacher.prototype.constructor value from Person to Teacher after setting the prototype to Person.

Object.defineProperty(Teacher.prototype, 'constructor', {
    value: Teacher,
    enumerable: false, // so that it does not appear in 'for in' loop
    writable: true });

Later near the end of the Trying the example out section, the finished version code uses this snippet as expected.

However a short while later in the finished version of the A further exercise section, the Teacher.prototype.constructor value and that of the new Student class are set using a different method.

Teacher.prototype.constructor = Teacher;
...
Student.prototype.constructor = Student;

Both approaches appear to have the same result in the console however I can’t find the explanation for the second method. I can follow the logic easily enough but unsure if I missed a comparison of the two ways of setting the Class/Constructor.prototype.constructor property. Is there one I overlooked?

Hello @horusofoz

The difference lays in the default values of configurable, enumerable and writable. There’s a comparison on the Object.defineProperty() page.

In the second version the property would, for example, be enumerable, which isn’t probably what you want, but i think this version was used to make it look cleaner and it doesn’t really matter for this exercise.

Cheers,
Michael

1 Like

Thank you @mikoMK for the explanation. A quick follow up. What scenarios would you want to prevent a property from being enumerable? If RAFO, feel free to say so.

1 Like

The constructor property is actually a good example of a “not-wanting-to-be-enumerable” property and the comment on your first code block above hints at the reason:
Think about using objects with arbitrary “key-value” pairs. They inherit some specialized functions from a parent object. Now, when you are using a for..in loop to loop over those properties you probably don’t want those functions and the constructor to be included.

1 Like