-1

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?

Little_idiot
  • 115
  • 7
  • That's a good question! But i think it does not suit this platform since it has already been answered several times here. https://stackoverflow.com/questions/3127429/ – kai Jul 14 '20 at 08:12
  • `this` shall always look in the current scope, in your example `sayHi` is a function, so when you call `this.name` there is no `name` property within the `sayHi` function scope, so you get undefined. You would need to bind the scope to that function or don't create a new function scope, see: https://repl.it/repls/SeparateFrillyApplicationframework#index.js – Alex Jul 14 '20 at 08:12
  • 2
    Does this answer your question? [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Yves Kipondo Jul 14 '20 at 08:14

1 Answers1

0

Actually this is passed as a default argument to all functions only

Note: Only function calls

What is happening in your code is that

when you execute var print = superman.sayHi() you call a function sayHi and this is passed by default

And in this case var print = superman.sayHi no value of this is passed.

So it prints undefined as the value of this.name.

You can either do this

var superman = {
name : 'Superman',
sayHi : "Hello, I'm "+name
};

//and then print sayHi

alert(superman.sayHi);
Rupesh Chaudhari
  • 193
  • 2
  • 2
  • 12