4

hi i am a little confusion on how exactly this works in javascript.Based on this example:

var myFunction = function(){
 function testMe(){
  console.log(this)  --------> DOMwindow
 }
 console.log(this) ---------> myFunction
}

var myvariable = new myFunction();

What is happening here?

  • 3
    Duplicates: http://stackoverflow.com/a/80127/710446 and http://stackoverflow.com/q/12370851/710446 – apsillers May 30 '13 at 01:42
  • 3
    Your `testMe` is never called? – Bergi May 30 '13 at 01:45
  • Searching is your friend. – user2246674 May 30 '13 at 01:45
  • ah, thanks i got answer from In Javascript, why is the "this" operator inconsistent? – Deepak Nair May 30 '13 at 01:47
  • 1
    @DeepakNair I'm glad you found your answer. Please do search on Google and other Stack Overflow answers first before posting a question. It helps us focus the site with high-quality questions and answers, and also if you post too many low-quality questions, you'll get an automatic question ban. –  May 30 '13 at 01:49

1 Answers1

5

The value this references depends on circumstances. Any unscoped (i.e. not in an object) function call will have this = window (DOMWindow, if you prefer). Anything that is part of a prototype, or has been changed using apply or bind, will have this as that object ("itself", if you prefer).

So, to illustrate. When you are instantiating using the new keyword, your function automatically inherits this as itself. When you call an IETF within it, this within this IETF will point to the global scope.

If you would like to avoid this, instead of calling testMe literally, you can always do this:

var myFunction = function() {
    var testMe = function() {
        console.log(this);
    }
    testMe.bind(this);
}

Which will, in turn, have this within testMe use the object as it should.

Sébastien Renauld
  • 17,611
  • 2
  • 38
  • 57
  • "The value this references changes on every function call based on what actually happens". Not at all. The value of *this* is set by the call and can be the same value every time. It can also be set to a fixed value using *bind* in ES5 compliant browsers. – RobG May 30 '13 at 02:22
  • @RobG: Fine, I'll edit to "the value this references is dependent on circumstances" to be more vague. – Sébastien Renauld May 30 '13 at 02:23
  • " When you are instantiating using the new keyword, your function automatically inherits this as itself". Not correct either. When a function is called as a constructor, its *this* references a newly constructed object. You've also ignored strict mode in ES5, where *this* can be **any** value, including undefined. – RobG May 30 '13 at 02:23