Function reference

Asked

Viewed 39 times

1

I would like to know why the function of the object is referencing to the name outside the object, and not to what is inside the object? the right would not be the function find the variable that is closest to the scope of the function?

const obj = {
    name : 'nome1',
    age : 21,
    funcaoObj () {
        return name
    }
}
 
name = 'name2'

console.log(obj.funcaoObj())

2 answers

4

You are accessing the scope of the function funcaoObj, however, as it was not found it rises one level to the global scope, the object itself does not have a scope as if it were a Class.

To access internally should be something like return obj.name. or use function

    function meu_objeto(){
         this.name = "name1";
         this.age = 21;
         this.funcaoObj = function(){
            return this.name;
         };
    };
    
    name = "name2";
    var teste = new meu_objeto();
    console.log(teste.funcaoObj());

  • then I must assume that the variables within a function are "hunted" within scopes ?

  • It’s something called Scope Activation Registry, a concept of programming language and compilers.

0

The name is a variable of window. Once you change the value, it will always have this value until you close the window.

When opening the window again, the value of name is null. When you set a value to it, this variable will always have that value while the window is open.

name = "nome2";
console.log(window.name);

After setting a value to name, give a refresh on the page and run the code below, without making any assignment to name will have the result:

<script>
// name = "nome2" comentado
console.log(name); // imprime "nome2" no console
</script>

inserir a descrição da imagem aqui

In case you want to return the name of its object and not of the variable of the window, would have to do so by adding a this:

const obj = {
    name : 'nome1',
    age : 21,
    funcaoObj () {
        return this.name
    }
}
 
name = 'name2'

console.log(obj.funcaoObj())

Browser other questions tagged

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