-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path03-scope.txt
74 lines (59 loc) · 1.71 KB
/
03-scope.txt
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
1. Al asignar una funcion a un variable se pierde el ambito
var x=10
var foo = {
x:11,
write:funcion(){console.log(this.x)}
}
foo.write() //11
var write = window.foo.write;
write() //10
window.x=10
window.foo = {
x:11,
write:function(){console.log(this.x)}
}
//this
window.foo.write() //11
//window
window.write = window.foo.write; //pierdes el ambito
//window.write = window.foo.write.bind(window.foo); //estableces el ambito
window.write = window.foo.write //pierdes el ambito
//widow
window.write() //10
explorador->window
nodejs->Global
2. Al pasar una funcion como parametro a otra funcion perdemos ambito
class Foo{
constructor(){
//new Bar(this.writer) //perdida de ambito
//new Bar(this.writer.bind(this)) //se establece
new Bar(()=>this.writer()) //2 llamadas en el stack no se pierde por la funcion flecha
}
writer(){
console.log(this)
}
}
class Bar{
constructor(writer){
writer() //undefined
this.writer = writer;
this.writer() //Bar
}
}
//https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Functions/Arrow_functions
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
//call y apply
bar = {}
function foo(lastName,firstName){
this.lastName =lastName
this.firstName = firstName
}
foo.call(bar,"Pedro", "Hurtado")
bar = {}
function foo(lastName,firstName){
this.lastName =lastName
this.firstName = firstName
}
foo.apply(bar,["Pedro", "Hurtado"])