-
Notifications
You must be signed in to change notification settings - Fork 4
CS classes and ES6 Classes (WIP)
One of the breaking changes that resulted from ES6 is the creation of the class
keyword. While there are quite a few shared idioms in the ES6 version, there are quite a few incompatibilities which have to be dealt with, especially since these features already existed in CS.
Here is a reference on ES6 classes
Here is a reference on CS classes
In reality CS expands on the ES native object {}
by adding member functions and member variables as prototype members of the object.
Part of this is how ES deals with the new
keyword. "using new with a constructor that returns an object will evaluate to the returned object, whereas returning any non-object will evaluate to the new instance." (From this post)
Basic CS Classes:
class A
class B extends class A
Which results in the following JS currently:
// Hoist our variables and a function to 'extend' one object
// by another by setting the child object's member prototypes from one object to another.
// The 'extend' function is only included if the `extend` keyword is used.
var A,
B,
extend = function(child, parent) {
for (var key in parent) {
// Set any non JS functions and properties to the child
if (hasProp.call(parent, key)) child[key] = parent[key];
}
// Establish prototype link, and correctly assign the constructor property for all instances of the child
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
},
// Shortcut function
hasProp = {}.hasOwnProperty;
A = (function() {
function A() {}
return A;
})();
B = (function(superClass) {
extend(B, superClass);
function B() {
return B.__super__.constructor.apply(this, arguments);
}
return B;
})(A = (function() {
function A() {}
return A;
})());
- class
- new
- extends
- super
- constructor
- @ (this)
- class
- new
- extends
- constructor
- super
- const
- __proto__
#Oddities of ES6 ES6 doesn't do class hoisting: in other words definitions of a class must occur before they are called/created.
ES6 can have a class definition: class Example {}
or named and unnamed class statements: var ex = class Example {}
and var ex = class {}
Definitions inside a class are run as if the strict
keyword is in effect.
ES6 classes allow only functions and methods, and don't support the notion of inline code within the class. CoffeeScript allows declaration of variables and random execution in the class definition.
ES6 uses the new Symbol primary type to evaluate instanceof
:
Making instanceof extensible. In ES6, the expression
object instanceof constructor
is specified as a method of the constructor:constructor[Symbol.hasInstance](object)
. This means it is extensible.