-1

In javascript all functions are objects. So how come when I use 'this' like so:

var myObj = function() {
    doSomething: function() {
        alert('msg');
    }

    myFunc2: function () {
        this.doSomething(); //'this' doesn't equal myFunc2, it's myObj
    }
}

'this' refers to myObj and not myFunc2? Javascript has function scope, 'this' is being used in myFunc2 so it should refer to myFunc2.

Why is this not the case? This language seems very inconsistent at times.

Legion
  • 3,295
  • 7
  • 39
  • 78
  • 2
    https://github.com/getify/You-Dont-Know-JS/blob/master/this%20&%20object%20prototypes/README.md – Michelangelo Nov 30 '15 at 16:54
  • Your code doesn't make much sense. You've got a function with two nested functions, but nothing ever calls them. – Pointy Nov 30 '15 at 16:54
  • This isn't even valid javascript? Did you mean for myObj to be an object and not a function? – Ben Lorantfy Nov 30 '15 at 16:55
  • 3
    `this` **never** refers to the function itself unless **explicitly** set so. How `this` works isn't that difficult, I suggest to read an article about it. – Felix Kling Nov 30 '15 at 16:55
  • Felix Kling: The fact that you and Pointy have left comments indicating the first 3 answers are incorrect or incomplete makes me think `this` isn't as straight forward as you assert. – Legion Nov 30 '15 at 17:09
  • Could be. Maybe I'm exposed to it for too long. The tl;dr version is: The value of `this` depends on how the function is **called**. There are four ways to call a function: as function, object method, as constructor (`new`) and `.call` / `.apply`. Exceptions: Bound functions (`.bind`) have a fixed `this` value. Arrow functions have "lexical" `this`. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this . Personally I don't find this too complicated :P – Felix Kling Nov 30 '15 at 17:16

1 Answers1

0

JavaScript doesn't have "function scope", what you are experimenting the how the this works in JavaScript.

The this keyword always reference the object that is calling the function, in this case, myObj.

Check this chapter from the You Don't Know JS book series to learn more about how this works in JavaScript:

You Don't Know JS: this & Object Prototypes

David Gomez
  • 2,672
  • 2
  • 15
  • 27