2 ms·
It's purely syntactic sugar. You can even get the new protection yourself: function Cat() { if (!(this instanceof Cat)) { throw new Error("p
by couchand 9y ago
It's purely syntactic sugar. You can even get the new protection yourself:
function Cat() {
if (!(this instanceof Cat)) {
throw new Error("please use new!");
}
}
or, if you want to be a bit nicer to your users:
function Cat() {
if (!(this instanceof Cat)) {
return new Cat();
}
}
- danlugo92 9y agoSeems like the 2nd option might prevent me from using Cat's as a mixin
- danShumway 9y agoBoth options will break mixins. function CatDog () { Cat.apply(this, arguments); } CatDog.prototype = Object.assign(Dog.prototype, Cat.prototype); In the above example, CatDog is not an instance of Cat, since it never actually inherits from the Cat prototype.
- hajile 9y agoMixins have terrible performance characteristics and lead to fragile code. While they were huge a few years ago, most new frameworks either avoid them or (in cases like React) chose to remove them for these reasons. In an existing codebase, that matters a lot. In newer codebases (or newer parts of existing ones) it shouldn't matter that much at all.
- spiralx 9y agoMixins in ES6 should be functions taking a class and returning another class that extends it: https://alligator.io/js/class-composition/ https://alligator.io/js/class-composition/