Doubt with scope js

Asked

Viewed 47 times

4

I know that variable statements are all high for the whole of the scope, but I was left with a little doubt about this, the use of the word 'use Strict' avoids q declare variables like this

a = 10

But why in this situation below it allows to show the value of this in the function even if with the word 'use Strict'.

function foo(){
    console.log(this); 
}

"use strict";
function minhaFuncao() {
  console.log(this); //Deveria ter mostrado undefined
 }
 myFunction();
 foo();

The elevation occurred and would have been like this ?

 function foo(){
   console.log(this);
 }

 function minhaFuncao(){
    console.log(this);
 }

'use Strict';

Is it right what I’m thinking ? , or something else happened, thanks in advance

1 answer

3


The this is not a variable, is the value corresponding to the execution context of a function. It is always present and cannot be declared.

In your case as the function does not belong to any object or class it has the window as an implementation context.

However you can limit the value this in global functions, or wherever the this would be the window. This has to do with security reasons, to avoid that via the browser console it is possible to change code values.

Look at the examples below:

class Foo {
  constructor() {
    this.name = 'classe';
  }
  foo() {
    console.log(this);
  }
}

new Foo().foo(); // Foo {name: "classe"}

const obj = {
  foo: function() {
    console.log(this); // {foo: ƒ, name: "objeto"}
  },
  name: 'objeto'
}

obj.foo();

function foo() {
  console.log(this === window);
}

foo(); // true

function bar(){
  'use strict';
  console.log(this); // undefined
}

bar();

That is, if the function does not belong to an object or class, it belongs to the object window by default but you can limit global access by using use strict.

  • I understood then in case it depends on the context in which this is employed, but the use of use Strict would not avoid iso ? or I’m wrong ?

  • 1

    Dear @Diogosouza he explained, this is not variable, and another thing use Strict does not change an "integer behavior", only changes the behavior for "strict" things, as avoid objects with duplicate keys, avoid set "undefined" variables and things like that. This will continue to be a "context"

  • @You can limit the value of this, I gathered more information in reply, I was just in a hurry. The use of use strict does not avoid the use of this but, yes, limits it if the execution context is global.

  • Okay, thank you very much

Browser other questions tagged

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