How does javascript work for this keyword?

I am developing JavaScript and I came across this problem. Consider the following code

var obj = {}; obj.bind = function () { console.info(this); }; obj.bind(); 

I am running the code in the FireBug JavaScript console. Expected Result: this displays a link to an object in the console.

It actually displays undefined .

But when I make this change to my code

 var obj = {}; obj.bind = function () { this.x = 'x'; console.info(this); }; obj.bind(); 

Now the console displays the expected value of this , which is a reference to the obj object.

Why is this happening?

+4
source share
2 answers

undefined is the return value of the function that you will get because you are not returning the value explicitly.

In Chrome and Firebug, it correctly displays the object in the console until the return value is undefined .

So, if you do:

 var obj = {}; obj.bind = function () { console.info(this); return "foo"; }; obj.bind(); 

... you should see something like:

 Object { } "foo" 

If Firebug does not display the object when it is empty, you may need to verify that you are using the latest version.

+3
source

In your example, "this" should be obj, as some commentators have noted. Here are the details that explain why -

In Javascript, the value of "this" changes depending on how you call the function:

  • When a function is stored as a property of an object and you call this function by calling obj.foo (), "this" will be obj.

Example:

 var obj = { x: 1, increment: function() { this.x = this.x + 1; }; obj.increment(); // Makes "this" be obj 
  • When you call a function using syntax that does not apply to any native object, this will be a global environment.

Example:

 function someFunc(a, b) { return a + b; // If you were to refer to "this" here, it would be the global env. } someFunc(5, 6); 
  • When you call a function as if it were a constructor using a new operator, a new object will be created for you, and "this" will point to this new object.

Example:

 function SomeConstructor() { this.x = 42; // under the hood, a new object was instantiated for you, and "this" was set to it. } var result = new SomeConstructor(); // note the "new" keyword 

// the result will be {x: 42}

  • When you use call () or apply (), you can control what "this" is.

(There is no example, since it is quite far from your question. See the docs for apply () or call () for an example.)

-1
source

All Articles