I am fairly new to JS, although I have decent experience in other languages.
From my understanding, in JS, when in a method, this
refers to it's owner object.
var superman = {
name : 'Superman',
sayHi : function(){
alert("Hello, I'm "+this.name)
}
};
When I write,
var print = superman.sayHi()
print()
It alerts, Hello, I'm Superman
as expected.
However, if I write,
var print = superman.sayHi
print()
It alerts, Hello, I'm undefined
Why does this happen? The this
in superman should refer to superman object, why is var print = superman.sayHi()
and var print = superman.sayHi
producing different outputs?