Take the 2-minute tour ×

I get confused on a JavaScript this reference situation.

I am working on a code that I declare function inside an object method. (The reason is to tidy up code inside an object method, while keeping the functions private to the method.)

The following is an experiment to re-produce my problem.

I found that the this inside greeting function refers to the window scope instead of person scope.

var person = {
    nickname: "Makzan",
    sayHi: function() {
        var greeting = function() {
            return "Aloha " + this.nickname;

(same code in jsfiddle: http://jsfiddle.net/makzan/z5Zmm/)

And this is the log result in browser:

> Object
> Window
Aloha undefined 

In JS, I know that this reference is tricky. And I can change the scope by using .call method to make this code works.

var greeting = (function() {
    return "Aloha " + this.nickname;

However, I am curious to know why by default the this refer to window scope inside the greeting method?

Thanks in advance for all your help.

share|improve this question
It is because greeting is called without a context. –  Arun P Johny Apr 5 '13 at 10:28
Thanks all. I learn more on what 'context' means now. –  Makzan Apr 5 '13 at 10:41
add comment

3 Answers

up vote 3 down vote accepted

this has nothing to do with scope. It is determined by context.

greeting() calls the function with no context, so this is the default object (window in a browser).

share|improve this answer
add comment

The this, references is not related to scope, it depends on the calling context.

As per the MDN doc,


share|improve this answer
add comment

Try person.nickname, this refers to the var greeting in your case

share|improve this answer
add comment

Your Answer


