-2

Will the following code return the same result? I can't really understand this keyword.

var o = {
    prop: 37,
    f: function () {
        return this.prop;
    }
};

console.log(o.f()); // logs 37


var A = {
    prop: 37,
    f: function () {
        return A.prop;
    }
};

console.log(o.f()); // logs 37
Tushar
  • 85,780
  • 21
  • 159
  • 179
Theof
  • 83
  • 1
  • 7
  • 2
    you're logging `o.f()` twice. why are you expecting a different result? – Fabrizio Calderan Jun 15 '15 at 14:47
  • the short answer is yes, because you're logging twice `o.f()`. The long answer is yes aswell, because `this.prop` is evaluated to `o.prop`, exactly like `A.prop`. – briosheje Jun 15 '15 at 14:50
  • In the second case, do `var B = A; A = null; console.log(B.f());`. Do the a similar thing for the first case. Do you see the difference now? – Felix Kling Jun 15 '15 at 15:12

2 Answers2

1

Yes, those two pieces of code will return the same result.

When a function is called as a method of an object, its this is set to the object the method is called on.

Here, the object invoking it is the same in both the cases.

The documentation on this can be helpful.

Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
Olivier Poulin
  • 1,778
  • 8
  • 15
1

(I'm going to assume you meant to call A.f() in the second part.

Yes, they will return the same result. The second example might make it hard to have two object instances that share the same function, but in many cases that doesn't really matter.

Except for certain "binding", or "hitching" situations that have to be manually set up, this can be determined from the dot before the method call.

iamthis.callmethod()

Katana314
  • 8,429
  • 2
  • 28
  • 36