-
Notifications
You must be signed in to change notification settings - Fork 277
/
4-scope.js
75 lines (45 loc) · 1.74 KB
/
4-scope.js
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
/* Ejemplo del universo, un sistema solar, y un planeta. */
// Scope es igual a, donde buscar por cosas (estás cosas son las variables), el Scope es el alcance que tienen las variables, depende de donde las declaremos y las mandamos llamar si tendremos acceso a ellas o no.
// Tenemos dos tipos de Scope, Scope Global y Scope Local.
// ===============
// Ejemplo de lo que es un Scope Global
var miNombre = "Diego";
function nombre() {
miNombre = "Alonso";
return miNombre;
}
nombre();
console.log(miNombre);
// Ejemplo de lo que es un Scope Local, el Scope local pasa al momento de crear una funcion, esto genera un ámbito diferente al global, al cual no se podrá tener acceso desde el ámbito global
var miNombre = "Diego"
function nombre() {
var miApellido = "De Granda";
return miNombre + " " + miApellido
}
nombre();
console.log(miNombre);
console.log(miApellido);
// Ejemplos de como puede ayuar o crear error el tema del scope.
// Ejemplo 1, cómo con una funcion podemos vambiar el valor de la variable global
var miNombre = "Diego"
function nombre(usuario) {
miNombre = usuario;
console.log(miNombre);
}
nombre("Oscar");
console.log(`Hola ${miNombre}, cómo estás?`);
// Ejemplo 2, cómo podemos evitar reescribir el valor de una variable gracias al scope,
var miNombre = "Diego"
function nombre(usuario) {
var miNombre = usuario;
console.log(miNombre);
}
nombre("Oscar");
console.log(`Hola ${miNombre}, cómo estás?`);
// Ejemplo 3, cómo si creamos un scope local, y mandamos llamar la variable fuera de la funcion, nos puede crear un problema.
function nombre(usuario) {
var miNombre = usuario;
console.log(miNombre);
}
nombre("Oscar");
console.log(`Hola ${miNombre}, cómo estás?`);