Skip to content

Instantly share code, notes, and snippets.

View mkczarkowski's full-sized avatar
馃殺
Shipping products

Marcin Czarkowski mkczarkowski

馃殺
Shipping products
View GitHub Profile
() => { ... } // brak parametr贸w
x => { ... } // jeden parametr, identyfikator
(x, y) => { ... } // kilka parametr贸w
// Funkcja z pojedynczym identyfikatorem, opuszczamy nawiasy otaczaj膮ce parametr.
[1, 2, 3].map(x => 2 * x); // [2, 4, 6]
// Funkcja wykorzystuj膮ca destrukturyzacje, pami臋tamy o u偶yciu nawias贸w.
[[1,2], [3,4]].map(([a, b] => a + b); // [3, 7]
// Funkcja z parametrem o warto艣ci domy艣lnej, nawiasy do boju.
const sayHello = (name="World") => console.log(`Hello ${name}`);
sayHello(); // 'Hello World'
// OK, brak bloku pozwala na wykorzystanie niejawnego return.
const sum = (a, b) => a + b;
// :(, ka偶de wywo艂anie zwr贸ci undefined, wewn膮trz blok贸w wymagane jest jawne return.
const sum = (a, b) => { a + b }
// OK, jawne return.
const sum = (a, b) => { return a + b };
const array = [1, 2, 3, 4, 5, 6];
// Rozwi膮zanie z u偶yciem deklaracji funkcji.
function isEven(num) {
return num % 2 === 0;
}
function square(num) {
return num * num;
}
// Deklaracja przodem.
function makeAdder(x) {
return function(y) {
return x + y;
}
}
// Do celu =>!
const makeAdder = x => y => x + y;
const sum = (a, b) // Syntax error.
=> { return a + b; };
const sum = (a, b) // Syntax error.
=> a + b;
const sum = (a, b) => // OK
{
return a + b;
};
asyncFunc.catch(x => { throw x });
// NOT OK, wywo艂anie zwr贸ci undefined
const baz = () => { foo: 'bar' };
// OK
const baz = () => ({ foo: 'bar' });
function Adder(value) {
this.value = value;
}
Adder.prototype.addToArray = function (arr) {
'use strict';
return arr.map(function (x) {
return x + this.value; // TypeError.
});
}
// Wi膮偶emy this z zakresu addToArray do funkcji mapuj膮cej za pomoc膮 bind().
Adder.prototype.addToArray = function (arr) {
return arr.map(function (x) {
return x + this.value;
}.bind(this));
}
// Korzystamy ze zmiennej pomocniczej self, w kt贸rej zapisujemy warto艣膰 wska藕nika this.
Adder.prototype.addToArray = function (arr) {
let self = this;