2

Consider the following JS object, it has:

  • x: a variable given value 100
  • p: prints value of x, called immediately after creation
  • y: prints value of x, called after object creation

When the value of Pipe.x is printed immediately during Object creation, for some reason Pipe.x is undefined but when P.y() is called, after an object, the Object has been created, the Value of Pipe.x is 100, as it should have been in the first place.

var Pipe = {
    x: 100,

    p: function(){
        console.log('p says x is ' + this.x); // prints y says x is undefined
    }(),    // call immediately

    y: function(){
        console.log('y says x is ' + this.x);
    }
}

Pipe.y();    // prints y says x is 100

Is there any JS object property I'm missing which makes Pipe.p() print undefined and P.y() print 100?

1 Answer 1

5

The this Context depends on how it is being called. When you call Pipe.y(), it is equivalent to obj.method() and this will be pointed to obj, in this case Pipe.

When p is being executed as IIFE, this is set to window and there is no x on window

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

1 Comment

Oh, that does make sense. Also, considering the above condition, is there any way that I can get value of x within p, even when p() is executed as IIFE?

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.