1

I am confused with the concept of JavaScript object referencing. Let's say we have an object with a method property called greet and we store the method in variable called sayIt. When we call that variable with the stored method property it returns undefined because it is referencing the global object instead of the person object with property firstName.

Why does it return undefined when it is referencing the object? Here is an example:

var person = {
  firstName : 'Boaz',
  lastName : 'Sender',
  greet : function() {
    console.log( 'Hi, ' + this.firstName );
  }
};

var sayIt = person.greet; // store the method in a variable

sayIt(); // logs 'Hi, undefined' -- uh-oh
Bryan
  • 2,860
  • 24
  • 37
  • 42
  • Methods are not "attached" to the objects. Methods literally have no idea what object it is called with until you call it. In case of `sayIt();` as you can see you don't have any object in the call. – zerkms Dec 09 '16 at 03:43
  • @AndrewLi: no, that question has nothing to do with it – Bergi Dec 09 '16 at 03:44
  • @Bergi It seems, my mistake. – Andrew Li Dec 09 '16 at 03:45
  • @zerkms It also helps calling them "functions" not methods. Only when you call the function on the object, it's a *method invocation* :-) – Bergi Dec 09 '16 at 03:45
  • JavaScript is object based and uses a *this context*. Not the definition, but the invocation sets the *this context*. When you call the method as a global variable, the this context will be the window object. Thus this.firstName references window.firstName, which is undefined. – Quasimodo's clone Dec 09 '16 at 03:45
  • try passing the context using `call` as in `var sayIt = person.greet.call(person);` or `person.greet();`. Hope it helps. – S.Dan Dec 09 '16 at 03:48
  • @Bergi and for that reason I don't like that the standard uses the "method" term at all - they are all functions. – zerkms Dec 09 '16 at 03:55

0 Answers0