Classes are purely syntactic sugar:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' says "hi"');
}
}
var a = new Animal('Paddington');
a.speak();
// => Paddington says "hi"
function Animal(name) {"use strict";
this.name = name;
}
Animal.prototype.speak=function() {"use strict";
console.log(this.name + ' says "hi"');
};
var a = new Animal('Paddington');
a.speak();
// => Paddington says "hi"
Traditional inheritance also works.
- An "iterator" is any object that implements a
next()
method- Returns an object
{ value: <any>, done: <boolean> }
- Either can be omitted
- Demo
- Need not be finite!
- Returns an object
- An "iterable" is any object that implements a
Symbol.iterator
method, which returns an iterator- e.g.
obj[Symbol.iterator] = function() { return { next: ... } }
- Implemented by many language built-ins:
String
,Array
,TypedArray
,Map
andSet
for...of
gives special treatment to iterables (whereasfor...in
just iterates over properties)- Demo
- Generators are also iterators... but that's a story for another day!
- e.g.
More: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/The_Iterator_protocol
Defining exports:
// in lib.js
export const MAGIC_NUM = 42;
export function square(x) {
return x * x;
}
// or: export { foo, bar };
// or: export { foo as herp, bar as derp };
Defining imports:
import { MAGIC_NUM, square } from 'lib';
console.log(square(MAGIC_NUM));
Re-exporting:
export { foo, bar } from 'src/other_module';
Module meta-data:
import { url } from this module; // "this module" is magic
console.log(url);
Allows programmatic access to module loading (and you can't just import
at top-level scripts):
System.import('some_module')
.then(some_module => {
some_module.doInterestingThings();
})
.catch(error => {
console.error(':(');
});
Returns a native Promise
, so Promise.all()
etc are all usable.
There's also a System.define()
for directly registering a named module.
The standard specifies several hooks to the module loader:
- Normalize: Given the import name, provide the canonical module name.
- Locate: Given a canonical module name, provide the URL for the resource.
- Fetch: Given a URL for a resource, fetch its content.
- Translate: Given module source, make any source modifications.
- Instantiate: Given module source, determine its dependencies, and how to execute it.
- es6-module-loader provides a polyfill
- SystemJS loads "any type of module"
- jspm installs from "any registry"
Good write-up: http://www.2ality.com/2014/09/es6-modules-final.html