-
Notifications
You must be signed in to change notification settings - Fork 0
/
losing this with callback functions.html
48 lines (39 loc) · 1.2 KB
/
losing this with callback functions.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>
<html>
<head>
<title>Losing "this" with callback functions</title>
</head>
<body>
<script type="text/javascript">
var firstName = "Grzegorz";
var lastName = "Skupiewski";
var obj1 = {
firstName: "Monia",
lastName: "Kubica"
}
var obj2 = {
firstName: "Paszczak",
lastName: "Skubica"
}
//przy uzyciu np. setTimeout tracimy znaczenie słowa this, które wraca z powrotem do obiektu globalnego
//sa dwa sposoby aby temu zapobiec
//przed funkcja przypisujemy this do that
//albo uzywamy metody .bind() aby stowrzyć nowa callback funckję, która będzie miała na stałe przypisane this do naszego
//this (zmienionego przez .call())
// var fullName = function() {
// //const that = this;
// setTimeout(function(){
// console.log(this.firstName + " " + this.lastName);
// }.bind(this),2000)
// }
//istnieje jeszcze sposób rozwiazania tego problemu poprzez uzycie arrow functions, ponieważ this zostaje wtedy przypisane leksykalnie - cos jak przy uzyciu bind()
var fullName = function() {
setTimeout(() => {
console.log(this.firstName + " " + this.lastName)
},2000)
}
fullName.call(obj1);
fullName.call(obj2);
</script>
</body>
</html>