-1

I found some code like this:

Function a(){ this.somevariable = ''; }

And some other code like this:

Function a(){ var somevariable = ''; }

The difference between them is the variable declaration. I need to know what is the this from this.somevariable. Is it different from var?

My real name
  • 417
  • 1
  • 3
  • 13
  • If you want to learn more, instead of posting to SO every time you run in the next little question, where you will often get answers which are misleading or incomplete, you should do what every other person in the history of computing has done when learning a new language which is to read the documentations, the intros, the tutorials, and the blog posts. After all, if you were learning Italian, would you post to an Italian site every time you ran into a word you didn't know, or would you study an Italian textbook? –  Sep 15 '17 at 04:35
  • For future reference, there is no need to include in your question personal details such as your history of learning the language, or your personal desires. They are irrelevant and distracting. To be perfectly honest, nobody cares. There is also no need to leave "thank you" comments on answers. If an answer was helpful, then upvote it. –  Sep 15 '17 at 04:37

1 Answers1

-1

this is a keyword in JavaScript.

function test(){
  this.x = 10;     
}  

in this case this represents the internal object, only can use in the function.

With the function of different occasions, this's value will change. But there is a general principle: this means the object which invoke the function.

Case 1: pure function call:

This is the most common use of the function, belongs to the global call. So this just means of the global object Global.

e.g:

function test(){
    this.m = 10;
    alert(this.m);
  }
  test(); // there alert 10

In order to prove this is a global object:

   var m = 10;
  function test(){
    alert(this.m);
  }
  test(); // 10

And:

   var m = 10;
  function test(){
    this.m = 0;
  }
  test();
  alert(m); // 10

Case 2: As the object which calls the function.

 

function test(){
    alert(this.m);
  }
  var obj = {};
  obj.m = 10;
  obj.n = test;
  obj.n(); // 10

Case 3:

As a constructor

function test(){
    this.m = 10;
  }
  var obj = new test();
  alert(obj.m); // 10

In order to show that this is not a global object in this case:

   var m = 10;
  function test(){
    this.m = 1;
  }
  var o = new test();
  alert(m); //10
aircraft
  • 16,211
  • 16
  • 74
  • 135
  • Ok thank sir @aircraft – My real name Sep 15 '17 at 04:10
  • Instead of writing the nine millionth description of `this` in JS, it would be much preferable to point the OP to an existing, comprehensive answer here on SO, or an authoritative web page such ashttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this. You can do that in a comment, not an answer. –  Sep 15 '17 at 04:44