.
. .
JavaScript- , , .
:
arr.forEach(func)funcforEach.setTimeout(func)func.- .
JavaScript.
. .
this
, "this", this. this, .
, :
let group = {
title: " ",
students: ["", "", ""],
showList() {
this.students.forEach(
student => alert(this.title + ': ' + student)
);
}
};
group.showList();
forEach , this.title , showList, group.title.
, :
let group = {
title: " ",
students: ["", "", ""],
showList() {
this.students.forEach(function(student) {
// Error: Cannot read property 'title' of undefined
alert(this.title + ': ' + student);
});
}
};
group.showList();
, forEach this=undefined , undefined.title.
, this.
new this : . new.
bind
=> , .bind(this) :
.bind(this).-
=>.this.this, : .
arguments
arguments.
, this arguments.
, defer(f, ms) , ms :
function defer(f, ms) {
return function() {
setTimeout(() => f.apply(this, arguments), ms);
};
}
function sayHi(who) {
alert(', ' + who);
}
let sayHiDeferred = defer(sayHi, 2000);
sayHiDeferred(""); // ", " 2
:
function defer(f, ms) {
return function(...args) {
let ctx = this;
setTimeout(function() {
return f.apply(ctx, args);
}, ms);
};
}
args and ctx, setTimeout .
:
, , , . .
<code>,<pre>, 10 (plnkr, jsbin, codepen)