Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

7
  • 1
    Why are you using setPrototypeOf()? At least according to MDN, it's generally discouraged to use it if you can accomplish the same thing by just setting the .prototype property on the constructor (as you're doing in the else block for browses that don't have setPrototypeOf). Commented Dec 22, 2016 at 21:23
  • Changing the prototype of an object is discouraged all together, not setPrototypeOf. But if you still need it (as OP asks), you should use the built-in methodology. As MDN indicates, this is considered the proper way to set the prototype of an object. In other words, MDN says do not change the prototype (as it affects performance and optimization) but if you have to, use setPrototypeOf. Commented Dec 23, 2016 at 11:58
  • My point was that I don't think you actually need to change the prototype here. You could simply use your line at the bottom (CustomError.prototype = Object.create(Error.prototype)). Also, Object.setPrototypeOf(CustomError, Error.prototype) is setting the prototype of the constructor itself rather than specifying the prototype for new instances of CustomError. Anyway, in 2016 I think there's actually a better way to extend errors, although I'm still figuring out how to use it together with Babel: github.com/loganfsmyth/babel-plugin-transform-builtin-extend/… Commented Dec 23, 2016 at 14:45
  • CustomError.prototype = Object.create(Error.prototype) is also changing the prototype. You have to change it since there is no built-in extend/inherit logic in ES5. I'm sure the babel plugin you mention does similar things. Commented Dec 23, 2016 at 19:03
  • 1
    I created a gist demonstrating why using Object.setPrototypeOf doesn't make sense here, at least not in the way you're using it: gist.github.com/mbrowne/4af54767dcb3d529648f5a8aa11d6348. Perhaps you meant to write Object.setPrototypeOf(CustomError.prototype, Error.prototype) - that would make slightly more sense (although still providing no benefit over simply setting CustomError.prototype). Commented Dec 27, 2016 at 2:22