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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
While other people have posted why this occurs (the understanding of
thisis incorrect), here is one solution which will work reliably.Update: As Raynos noted, when using strict mode functions in ECMAScript 5th Edition, it is invalid to use
arguments.callee(it will throw a TypeError). Thus caution should be exercised if using this approach. (When using a [correct] ECMAScript 5th edition engine, there is no reason to usearguments.calleeover the name given to the function which is bound to the new scope — see the end of the answer.)Another is to use a closure:
Or, a closure over a variable directly:
Or… so many ways.
Happy coding.
Another approach that was pointed out by Aadit M Shah is to use the function identifier to refer to the current function:
As Aadit points out, this is valid, as per the ECMAScript 5th edition specification, page 99:
However, some browsers (at least IE9) implements this incorrectly (and I am not sure if the above noted behavior is well-defined in the 3rd edition). Consider:
In IE9 it will yield 42 and in FF8 it will yield the function-object. IE9 is incorrect here as it introduces
yas a variable in the enclosing scope, which is forbidden by ECMAScript for function expressions. Here is an in-context example of how this incorrect implementation can lead to different results: