Reputation: 14866
What makes ES6 class syntax better than traditional prototype approach?
Should I replace all my current objects with classes since I don't care about the cross browser stuff?
Upvotes: 6
Views: 3216
Reputation: 21926
For the most part classes are just syntactic sugar over the old way. We'll get back to that in a minute, but there is at least one thing classes can do that the old way can't: properly extend built-in constructors like Array and HTMLElement. Additionally, classes will automatically throw when not called with new
whereas the old way was to add an instanceof
check in the constructor.
Now for the sugar, consider this old-style constructor function:
function Foo(bar) {
this._bar = bar;
Object.defineProperty(this, 'bar', {
get: function() { return this._bar },
set: function(value) {
console.log(value);
this._bar = value;
}
});
};
Foo.prototype.someMethod = function() { return this.bar + 5 };
Foo.someStaticMethod = function() { return 3 };
That's kinda... ugly. Consider the equivalent class:
class Foo {
static someStaticMethod () {
return 3;
}
constructor (bar) {
this._bar = bar;
}
get bar () {
return this._bar;
}
set bar (value) {
console.log(value);
}
someMethod () {
return this.bar + 5;
}
}
Much cleaner. Whether or not you should re-write existing code is more of a toss-up, but definitely use classes for the new stuff.
Upvotes: 1
Reputation: 2130
ES6 class based syntax is much better than traditional prototype approach,
Compared to constructors and constructor inheritance, classes make it easier for beginners to get started.
Subclassing is supported within the language.
Built-in constructors are subclassable.
No library for inheritance is needed, anymore; code will become more portable between frameworks.
They provide a foundation for advanced features in the future (mixins and more).
So if you don't care about cross browser, then go with class based syntax.
Happy coding!!
Upvotes: 1
Reputation: 3734
ES6 classes are a simple sugar over the prototype-based OO pattern. Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability. Classes support prototype-based inheritance, super calls, instance and static methods and constructors.
Upvotes: 2