4

I've gotten to the point where I am trying to fill out my javascript knowledge with some of the more advaned concepts.

I think I a pretty much understand how scope works. Where objects inherit from a prototype and then global scope, while functions offer a more traditional block scope within themselves.

What I am have trouble understanding is this:

function a(){
  console.log(this.z);
  }

a.z = 12;

a(); //returns undefined :(

I was expecting to echo out 12, but of course, it doesn't. Where exactly is z being stored? what does "this" refer to in the example?

3
  • A(); will ignore the z to be set. You can do: a = new a(); and a.z = 12; Commented May 12, 2014 at 6:21
  • this does not (usually) refer to the function-object (and is not related to the scope of the function at all!); rather, it refers to the "context" of the function Commented May 12, 2014 at 6:25
  • See stackoverflow.com/questions/3127429/javascript-this-keyword Commented May 12, 2014 at 6:27

1 Answer 1

2

When you call a function, JavaScript will set the current context (this) as the object on which it is called. If the function is not attached to any object, by default global object (window object in browsers) will be used *.

So, in this case, this refers to the global object, not a. In the global object, z hasn't been defined yet. That is why it returns undefined.

To get the value 12, you need to access it like this

function a() {
    console.log(a.z);   // Use `a` itself, instead of `this`.
}

a.z = 12;

a();

* In strict mode, this will be set to undefined, if the function is called without any explicit object reference.

Sign up to request clarification or add additional context in comments.

1 Comment

Light bulb went off. A lot of code patterns I have been seeing make sense now. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.