When assigning an attribute to a function, is it as if I have created a variable within that function?

1

I'm studying JS, so I understand, when assigning an attribute to a function, it's like creating a variable within that function, is that it? for example:

Original function:

function copaMundo() {} 

Assigning a property and an attribute to the function:

copaMundo.pais = "Rússia"; 

Would this be the end result:?

function copaMundo() {
    var pais = "Rússia";
}
    
asked by anonymous 14.06.2018 / 21:04

2 answers

1

I do not know where this idea came from but that's not quite it, notice the example:

function copaMundoA() {
  console.log(1, typeof pais, copaMundoA.pais); // undefined Ruússia
}
copaMundoA.pais = "Rússia";
copaMundoA();

/****************************/

function copaMundoB() {
  var pais = "Rússia";
  console.log(2, typeof pais, pais); // string Rússia
}
copaMundoB.pais = "Rússia";
copaMundoB();

Properties assigned to a function are not available "globally" in the scope of the function. You can access them if the function has name via fn.prop as in the example.

Variables declared within the function are closed in this scope and therefore not accessible. If you want to have private scope variables you can use an IIFE and thus create a private memory of the function:

var copaMundoA = (function() {
  var pais = 'Rússia';
  return function() {
    console.log(1, pais); // Ruússia
  }
})();

copaMundoA();

console.log(2, typeof pais); // undefined
    
14.06.2018 / 21:18
0

No, it's different .. In your example, the variable declared inside the function ( var pais ) in the last code can not be accessed outside of function , it is local to function only, see example:

var func = function() { 
   var sobrenome = "da Silva"; 
   this.idade = 20;
};

func.nome = "João";

// acessível 
console.log(func.nome);  
// não acessível
console.log(func.sobrenome);
// não acessível
console.log(func.idade);
    
14.06.2018 / 21:22