Square.prototype.constructor on page 75 in The principles of OOJS should be non-enumerable

14 views
Skip to first unread message

Martin Rumpler

unread,
Oct 31, 2019, 2:02:18 PM10/31/19
to Zakas Books
On page 75 in your book "The principles of object-oriented JavaScript" you give an example how to set the Square.prototype. The constructor property is  defined with enumerable:true but I think this is an error. It should be non-enumerable.

function SuperType() {}

function SubType() {}
console.log(SubType.prototype.propertyIsEnumerable('constructor')); // false

SubType.prototype = Object.create(SuperType.prototype);
SubType.prototype.constructor = SubType;
console.log(SubType.prototype.propertyIsEnumerable('constructor')); // true

SubType.prototype = Object.create(SuperType.prototype, {
    constructor : { value:SubType, writable:true, enumerable:false, configurable:true }
});
console.log(SubType.prototype.propertyIsEnumerable('constructor')); // false

By the way: Wouldn't it be always safer and easier to use the following method of changing the prototype:

Object.setPrototypeOf(SubType.prototype, SuperType.prototype);
console.log(SubType.prototype.propertyIsEnumerable('constructor')); // false

Nicholas Zakas

unread,
Nov 1, 2019, 4:01:26 PM11/1/19
to zakas...@googlegroups.com
Hi Martin,

It looks like you're correct, that example (and the one at the beginning of the section) should both be using enumerable: false. I'll make a note of that.

With regards to your second question, you certainly can adjust the prototype that way, though it's not idiomatic for JavaScript. It's just as safe to say SubType.prototype = Object.create(SuperType.prototype) and a bit more idiomatic. The example in the book was meant to show that you can inherit from another prototype and add new properties in one step, with is where Object.create() really has an advantage.

Thanks for reaching out.

--
You received this message because you are subscribed to the Google Groups "Zakas Books" group.
To unsubscribe from this group and stop receiving emails from it, send an email to zakasbooks+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/zakasbooks/ac528d77-0631-4641-aa75-d97a332c54ae%40googlegroups.com.


--

______________________________
Nicholas C. Zakas
@slicknet

Author, Principles of Object-Oriented JavaScript
Reply all
Reply to author
Forward
0 new messages