Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"this" refers to something else?

Tags:

javascript

When I run this code:

var Test = function() {
    return this.stuff;
};

Test.stuff = 'Neat!';

document.write(Test() || 'Not neat.');

Why do I get 'Not neat.'? Why can't I access the stuff property using this.stuff?

like image 769
AlicanC Avatar asked May 20 '26 15:05

AlicanC


1 Answers

This is what you have done:

var Test = function() {                //Test is a Function object
    return this.stuff;                 //this is a pointer to an object, not Test
};

Test.stuff = 'Neat!';                  //Add a property to Test

document.write(Test() || 'Not neat.'); //this has no property stuff

Change the last line of your code to:

document.write(Test.call(Test) || 'Not neat.'); //this now points to Test

The reason your code didn't work is because the this pointer points:

  1. The instance of the constructor created when the function call is prefixed with the new keyword. (e.g. var foo = new Foo(); //the this in Foo points to foo [for the sake of explanation]).
  2. The object passed to the call and apply functions as the first parameter.

What you want to do instead is something like:

var Test = function Temp() {           //Test is a Function object, alias Temp
    return Temp.stuff;                 //Temp is the same as Test, only locally
};

Test.stuff = 'Neat!';                  //Add a property to Test

document.write(Test() || 'Not neat.'); //writes Neat!

Upvote this answer if you liked it. Cheers.

like image 97
Aadit M Shah Avatar answered May 23 '26 03:05

Aadit M Shah