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?
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:
new keyword. (e.g. var foo = new Foo(); //the this in Foo points to foo [for the sake of explanation]).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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With