- anonymous function
function (x) { ... }
arguments
point to the parameterrest
function foo(a, b, ...rest) {
console.log('a = ' + a);
console.log('b = ' + b);
console.log(rest);
}
foo(1, 2, 3, 4, 5);
// a = 1
// b = 2
// Array [ 3, 4, 5 ]
foo(1);
// a = 1
// b = undefined
// Array []
- global object
window
- local scope, use
let
instead ofvar
- naming space, bind variables and function to a unique global variable
- constants,
const
this
point to current object- apply
function.apply(object, [array])
//this
bind to first parameterobject
,array
is function's parameters - call
function.apply(object, parameter1, parameter2, ...)
//this
bind to first parameterobject
,parameter1, parameter2, ...
is function's parameters
'use strict';
function pow(x) {
return x * x;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var results = arr.map(pow); // [1, 4, 9, 16, 25, 36, 49, 64, 81]
- reduce
[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)
- filter
- sort
'use strict';
var arr = [10, 20, 1, 2];
arr.sort(function (x, y) {
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
return 0;
});
console.log(arr); // [1, 2, 10, 20]
- Returning Functions, return function instead of value, could get the value of this function only when you called it.
- private variable
'use strict';
function create_counter(initial) {
var x = initial || 0;
return {
inc: function () {
x += 1;
return x;
}
}
}
this
always point to lexical scope
function* foo(x) {
yield x + 1;
yield x + 2;
return x + 3;
}
f.next
for ... of