Function Reference

2

I would like to know why the object's function is referencing the name outside the object, not what's inside the object? what would not be the function to look for 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())
    
asked by anonymous 04.04.2018 / 05:49

2 answers

5

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

To access internally it 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());
    
04.04.2018 / 06:09
1

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

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

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

After setting a value to name , refreshing the page and executing the code below, without doing any assignment to name will have the result:

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

Ifyouwanttoreturnthenameofyourobjectandnotthevariableofwindow,youwouldhavetodothisbyaddingathis:

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

console.log(obj.funcaoObj())
    
04.04.2018 / 06:46