Skip to content

Instantly share code, notes, and snippets.

@Y2017
Last active February 28, 2017 16:26
Show Gist options
  • Save Y2017/926a9a84ba642874ed2b0a0ff0a612b9 to your computer and use it in GitHub Desktop.
Save Y2017/926a9a84ba642874ed2b0a0ff0a612b9 to your computer and use it in GitHub Desktop.
ES6
// this
// JS Function : Without using the "strict" mode, this refers to the context in which someFunction() was called
// In "strict" mode, this would be undefined, which is slightly less confusing.
// http://jsbin.com/vekawimihe/2/edit?js,console
// When this is used inside an arrow function JavaScript uses the this from the outer scope
// class
class Hamburger {
constructor() {
// This is the constructor.
}
listToppings() {
// This is a method.
}
}
// object
let burger = new Hamburger();
burger.listToppings();
// inheritance
// ES6 classes provide a syntactic sugar attempting to alleviate the issues with using prototypical inheritance present in ES5
// Base Class : ES6
class Bird {
constructor(weight, height) {
this.weight = weight;
this.height = height;
}
walk() {
console.log('walk!');
}
}
// Subclass
class Penguin extends Bird {
constructor(weight, height) {
super(weight, height);
}
swim() {
console.log('swim!');
}
}
// Penguin object
let penguin = new Penguin(...);
penguin.walk(); //walk!
penguin.swim(); //swim!
//----------------------------------
// JavaScript classical inheritance.
// Bird constructor
function Bird(weight, height) {
this.weight = weight;
this.height = height;
}
// Add method to Bird prototype.
Bird.prototype.walk = function() {
console.log("walk!");
};
// Penguin constructor.
function Penguin(weight, height) {
Bird.call(this, weight, height);
}
// Prototypal inheritance (Penguin is-a Bird).
Penguin.prototype = Object.create( Bird.prototype );
Penguin.prototype.constructor = Penguin;
// Add method to Penguin prototype.
Penguin.prototype.swim = function() {
console.log("swim!");
};
// Create a Penguin object.
let penguin = new Penguin(50,10);
// Calls method on Bird, since it's not defined by Penguin.
penguin.walk(); // walk!
// Calls method on Penguin.
penguin.swim(); // swim!
// let is also useful when used in a for loop.
//For example, without let, the following example would output 5,5,5,5,5:
for(var x=0; x<5; x++) {
setTimeout(()=>console.log(x), 0)
}
// However, when using let instead of var, the value would be scoped in a way that people would expect.
for(let x=0; x<5; x++) {
setTimeout(()=>console.log(x), 0)
}
// Spread Operator
// ---------------
// an in-place expansion of an expression
//arrays can now be concatenated with ease:
let cde = ['c', 'd', 'e'];
let scale = ['a', 'b', ...cde, 'f', 'g']; // ['a', 'b', 'c', 'd', 'e', 'f', 'g']
// object literals can be concatenated:
let mapABC = { a: 5, b: 6, c: 3};
let mapABCD = { ...mapABC, d: 7}; // { a: 5, b: 6, c: 3, d: 7 }
// spread operator in a function call
const add = (a, b) => a + b;
let args = [3, 5];
add(...args); // same as `add(args[0], args[1])`, or `add.apply(null, args)`
// Rest arguments (in a function call)
// -----------------------------------
// Rest arguments are used to access a variable number of arguments passed to a function.
// it collects an indefinite number of comma separated expressions into an array
function add(...numbers) {
return numbers[0] + numbers[1];
}
add(3, 2); // 5
// or in es6 style:
const addEs6 = (...numbers) => numbers.reduce((p, c) => p + c, 0);
addEs6(1, 2, 3); // 6
// accessing rest arguments and/or arguments
function print(a, b, c, ...more) {
console.log(more[0]);
console.log(arguments[0]);
}
print(1, 2, 3, 4, 5);
// 4
// 1
// Destructuring
// --------------
// Destructuring is a way to quickly extract data out of an {} or []
// with array []
let foo = ['one', 'two', 'three'];
let [one, two, three] = foo;
console.log(one); // 'one'
// with json object {}
let myModule = {
drawSquare: function drawSquare(length) { /* implementation */ },
drawCircle: function drawCircle(radius) { /* implementation */ },
drawText: function drawText(text) { /* implementation */ },
};
let {drawSquare, drawText} = myModule;
drawSquare(5);
drawText('hello');
// with objects arguments in a function (destructured arguments)
// Destructuring can also be used for passing objects into a function
let jane = { firstName: 'Jane', lastName: 'Doe'};
let john = { firstName: 'John', lastName: 'Doe', middleName: 'Smith' }
function sayName({firstName, lastName, middleName = 'N/A'}) {
console.log(`Hello ${firstName} ${middleName} ${lastName}`)
}
sayName(jane) // -> Hello Jane N/A Doe
sayName(john) // -> Helo John Smith Doe
// String interpolation
// ES6 introduces a new type of string literal that is marked with back ticks (`)
console.log(`hello my name is ${name}, and I am ${age} years old`);
// Modules
/**
* extract data from arrays or objects
*/
// A module in ES6 is single file that allows code and data to be isolated
// In other languages it's called a package or library
// utils.js
export const pi = 3.14;
export function add(x, y){
return x + y;
}
// index.js
import {pi, add} from utils;
/**
* Generators are functions which can be paused and resumed later. Function
* context is saved across resumes.
*/
function* count(){
var start = 0;
while(true) {
yield start;
++start;
}
}
var iterator = count();
iterator.next(); //{value: 0, done: false}
iterator.next(); //{value: 1, done: false}
iterator.next(); //{value: 2, done: false}
iterator.return();
/**
* Map object are simple key/value maps. Both object and primitive values can
* be used as key or value in map.
* Although Map looks similar to Object, its worth noting that keys of Object
* are strings while there is no such restriction for a Map. Also Map size can
* be retrieved like an array while this is not the case with Objects.
*/
var x = {};
var y = 9;
var z = "foo";
var m = new Map();
m.set(x, 34);
m.set(y, "bar");
m.set(z, {data: "test"});
m.get(x); // 34
m.get(y); // "bar"
m.get(z); // {data: "test"}
m.size; // 3
// ---------------------------------
/**
* Set is a collection of unique values. A Set can be iterated in order of
* insertion of its elements.
*/
var foo = new Set();
foo.add(1);
foo.add(2);
foo.add("three");
foo.has(1); // true
foo.size; // 3
foo.delete(2); // removes 2 from foo
/**
* Promises are used for deferred and asynchronous computations.
* A Promise represents an operation that hasn't completed yet, but is expected in the future.
*/
var foo = new Promise(function (resolve, reject) {
//Check if the current timestamp is an even number and resolve
if (Date.now() % 2 === 0) {
//Pass a status code of 200 to the success callback function
resolve(200);
} else {
//Pass a status code of 404 to the failure callback function
reject(404);
}
});
//When the promise has successfully resolved, execute the following
//callback function
foo.then(function (status) {
console.log("Successfully resolved: " + status);
});
//When the promise is rejected i.e. an error, execute the following
//callback function
foo.catch(function (status) {
console.log("An error occurred: " + status);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment