js0010

使用箭头函数来绕过函数上下文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>
<head>
<title>Using arrow functions to work around callback function contexts</title>
<meta charset="utf-8">
<script src="../assert.js"></script>
<link rel="stylesheet" type="text/css" href="../assert.css">
</head>
<body>
<button id="test">Click Me!</button>
<script>
function Button() {
this.clicked = false;
this.click = () => {
this.clicked = true;
assert(button.clicked, "The button has been clicked");
}
}
var button = new Button();
var elem = document.getElementById("test");
elem.addEventListener("click", button.click);
</script>
</body>
</html>