ESNext Class
2 min readSep 30, 2016
esnext class
es5
class-like
function Point(x, y) {
this.x = x;
this.y = y;
}Point.prototype.toString = function() {
return '(' + this.x + ', ' + this.y + ')';
}var p = new Point(2, 2);
p.toString();console.log(p instanceof Point); // true
console.log(p instanceof Object); // true
es6
class
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}let p = new Point(2, 2);
p.toString();
console.log(p instanceof Point); // true
console.log(p instanceof Object); // true
console.log(typeof Point); // function
console.log(typeof Point.prototype.toString); // function
compatable class
- class is not hoisted, see temporal dead zone
- class runs in strict mode
- all methods are noe enumerable
- class will throw an error without new operator
'use strict';var _createClass = function() {Get Jackie Park’s stories in your inbox
Join Medium for free to get updates from this writer.
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}var Point = function() {
function Point(x, y) {
_classCallCheck(this, Point); this.x = x;
this.y = y;
} _createClass(Point, [{
key: 'toString',
value: function toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}]); return Point;
}();let Point = (function() { "use strict"; const Point = function(name) { // make sure the function was called with new
if (typeof new.target === "undefined") {
throw new Error("Constructor must be called with new.");
} this.name = name;
} Object.defineProperty(Point.prototype, "toString", {
value: function() { // make sure the method wasn't called with new
if (typeof new.target !== "undefined") {
throw new Error("Method cannot be called with new.");
} console.log(this.name);
},
enumerable: false,
writable: true,
configurable: true
}); return Point;
}());




