3

I'm still confused when it comes to scope when working with object's methods. In the code below I have two neighbors. Each has it's own method.

var counter = 0;
var neighbor1 = {
  name: 'John',
  myFunction: function () {
    console.log(this.name)
    this.doStuff();
  }
};
var neighbor2 = {
  name: 'Bob',
  doOtherStuff: function () {
    console.log(this.name);
    if(counter>5) {
      return false;
    } else {
      counter++;
      this.myFunction();
    }
  }
};

neighbor1.doStuff = neighbor2.doOtherStuff;

neighbor1.myFunction();

I understand when I call the neighbor1.myFunction method that it will call the neighbor2.doOtherStuff method because I've used the assignment operator above. What I don't understand is why 'this' will always be the neighbor1 object (John) and never the neighbor2 object (Bob). Can someone please explain in simple terms why neighbor1 is always 'this'? Thanks!

1 Answer 1

1

this is always referring/pointing to execution context(from where you executing the function, not from where you writing the function). You're invoking this.doStuff() at neighbor1 and hence the this is always pointing to neighbor1.

If you wish to understand more about this, I would recommend study this awesome material

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

Comments

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.