Overview
class User {
constructor(name, address) {
this.name = name;
this.address = address;
}
method() { return 4; }
static m(a, b) { return 5; }
}
const us = new User('JC', 'my address');
us.name // JC
us.method() // 4
User.m(3,4) // 5
class SuperUser extends User {
constructor(name, address, group) {
super(name, address);
this.group = group;
}
method() { return super.method()+1;}
}
class User {
constructor(name, address) {
this._name = name;
this._address = address;
}
get name() { return this._name;}
set name(newname) { this._name = newname; }
}
const us = new User('JC', 'my address');
us.name // JC
us._name
, it is not privateimport {fun} from 'npmmod';
import {fun} from './mod';
import {fun, fun2, fun1 as foo} from 'mod';
import default from 'mod'
mod.fun
, mod.fun2
, etc.import default as othername from 'mod'
export
in front of the definitionIf the file extension is .mjs
, node understands this file to be in ES6 syntax. If the file extension is .js
and the package.json
has a "type": "module"
line, node also understands this file to be in ES6 syntax.
function User(name) {
this.name = name;
}
var bob = new User('Bob');
console.log(bob.name); // 'Bob'
// ES5 adding a method to the User prototype
User.prototype.walk = function() {
console.log(this.name + ' is walking.');
};
var bob = new User('Bob');
bob.walk(); // 'Bob is walking.'
// ES5 Prototype inheritance
function Nerd(name, programmingLanguage) {
this.name = name;
this.programmingLanguage = programmingLanguage;
}
Nerd.prototype = new User('x');
Nerd.prototype.code = function() {
console.log('The nerd called ' + this.name + ' is coding in ' + this.programmingLanguage + '.');
};
var jc = new Nerd('JC', 'JavaScript');
jc.walk(); // 'JC is walking.'
jc.code(); // 'The nerd called JC is coding in JavaScript.'