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