0

Initial question

The below code should return 1,3 since x: 1 is just present above return statement - however, it's returning 3,1. Why is this? Will it be same result when we use let and/or const.

It would be great if you guys explain, so that I can improve my fundamentals. Below is my code:

var x = 3;

var foo = {
  x: 2,
  baz: {
    x: 1,
    bar: function() {
      console.log("this--->", this);
      return this.x;
    }
  }
}

var go = foo.baz.bar;

alert(go());
alert(foo.baz.bar());

Update 1:

In the first case bar is considered as a closure which has access to the variables outside and prints 3:

bar: function() { console.log("this--->", this); return this.x; }

Tom O.
  • 5,133
  • 2
  • 19
  • 33
  • `since x =1 is just present above return statement.` Well, it's not just above the `return` statement. It's outside of the function that contains that, and so it has a different scope than the function. – Scott Marcus Jun 17 '19 at 20:31
  • @ScottMarcus hey thanks, can you let me know why its marked as negative I researched and posted :( –  Jun 17 '19 at 21:01
  • 1
    Your question is really one of how scope and `this` binding works in JavaScript and that has been asked and answered literally hundreds of times. – Scott Marcus Jun 17 '19 at 21:08
  • I tried searching but didn't find any suitable answers... can you please help in removing negative marks –  Jun 17 '19 at 22:12
  • The only way to remove downvotes is for the person who did it to retract it. The best way to not get downvotes is to thoroughly research your issue prior to posting. If you were to search Stack Overflow or even Google for "How does JavaScript scope work?" or "How does this binding work in JavaScript?" you will find all kinds of pages that explain this issue. – Scott Marcus Jun 18 '19 at 12:43

3 Answers3

0

When you assign foo.baz.bar to a var go, after the assignment go just holds a reference to the inner function. If it is then called from the outer scope then x = 3. In effect, the this within a function depends on the scope that the function is called from.

In the second case, when you call bar(), it is in the scope of the object it's called from within (i.e. foo.baz ), so this time the this within function bar() refers to baz, giving and so x = 1.

More on scope and this in javascript here

Will Jenkins
  • 7,578
  • 1
  • 20
  • 35
0

The 'this' keyword will mean two different objects for the two function calls. You may see it by adding 'console.log(this);' before the return statement. Try using an arrow function instead!

Strider2342
  • 63
  • 1
  • 7
0

Here you can read up on Function.prototype.bind. This method should be able to help you out with your issue.

Check the code example below:

var x = 3;

const foo = {
  x: 2,
  baz: {
    x: 1,
    bar: function() {
      return this.x;
    }
  }
}

//You're assigning a function definition to a variable, but this will not maintain scope:
const fn = foo.baz.bar;

//When called like this, bar() can be thought of as a method of foo.baz
console.log(foo.baz.bar()); //so we expect x = 1;

//You must properly bind your function reference to the desired "this" object:
const globalBound = fn; //which would be equivalent of: fn.bind(this);
const fooBound = fn.bind(foo);
const bazBound = fn.bind(foo.baz);

console.log(globalBound()); //x = 3
console.log(fooBound());    //x = 2
console.log(bazBound());    //x = 1

x = 'Now globalBound() will return a string';
foo.x = 'and so will fooBound(), but bazBound() will remain unchanged';

console.log(globalBound());
console.log(fooBound());
console.log(bazBound());

I encourage you to change var x = 3 to let x = 3 and check out your result.

Tom O.
  • 5,133
  • 2
  • 19
  • 33
  • hey my code didnt have bind, can you explain with a diagram its so hard to understand :( –  Jun 17 '19 at 20:40
  • I don't have a diagram, but basically what `bind` is used for is to map `this` to a particular value within a function. The first argument passed to `bind` should be the object you want to use as the `this` value. Read that MDN article by using the link I posted and it should help clarify. – Tom O. Jun 17 '19 at 20:43
  • hey thanks, can you let me know why its marked as negative I researched and posted :( –  Jun 17 '19 at 20:44
  • I think that just means someone down-voted the question. It's probably because your question is posted in bullets and could probably be phrased more lucidly (not worth a down vote IMO) - maybe try just rephrasing the question a little more clearly. – Tom O. Jun 17 '19 at 20:47