When assigning an attribute to a function, is it like creating a variable within that function?

Asked

Viewed 35 times

1

I’m studying Javascript and, as I understand it, when assigning an attribute to a function, it’s like creating a variable within that function, that’s it?
For example:

Original function:

function copaMundo() {} 

Assigning a property and an attribute to the function:

copaMundo.pais = "Rússia"; 

Serious that the final result:?

function copaMundo() {
    var pais = "Rússia";
}

2 answers

1

I don’t know where you read that idea but that’s not quite it, look at 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 is named 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 scoped 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

0

No, it’s different.. in your example, the variable declared within the Function (var pais) in the last code cannot be accessed outside the Function, is local to Function only, see the 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);

  • In this case, it’s as if he "added" a variable within the function, but it’s a type of global variable, would you be serious about that? the last question is this: anonymous functions are functions that have no name, but when you assign a function to a variable, technically it has a name, or am I mistaken? for example: in the example given by vc, vc assigned a function to the variable "func", this does not make the function no longer anonymous?

  • Yes, it’s about that, the function is treated as if it were an object, and you added an attribute to it. Yes is an anonymous function, and when you assign it to a variable, which is from where the function can be executed since it does not have a name, it is called a function expression (Function Expression): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function

Browser other questions tagged

You are not signed in. Login or sign up in order to post.