1

I may be misunderstanding something here, but why do my this / self always output the entire Window object into the console?

var myViewModel = function() {
    var self = this;
    console.log('My viewModel');
    console.log(self);
}();

This results in following console output

enter image description here

Am I completely misunderstsanding this object?

solefald
  • 1,479
  • 1
  • 12
  • 28
  • 1
    Possibly Related: http://stackoverflow.com/questions/20210978/difference-between-using-variable-self-vs-this – Justin E Dec 17 '14 at 20:59
  • 1
    Usually self is the last instantiated object in this case, you are setting it to `this`, so logging `self` will log the contents of `this` – Justin E Dec 17 '14 at 21:01
  • I just realized that i've been using `var blah = function() {}`, instead of `function blah() {}`. Second one gives me the expected result! Argh. – solefald Dec 17 '14 at 21:02
  • 3
    No, the problem is that you have the `()` in the last line. It calls the function **immediately** and assigns the return value (`undefined`) to `myViewModel`. – Felix Kling Dec 17 '14 at 21:03

1 Answers1

1

Am I completely misunderstsanding this object?

Could be, but I don't know what you expect, so I can't answer that.

The reason why this refers to window is that the function is executed immediately. In a function executed as foo() (non-strict mode), this refers to the global object (window).

Note the () at the end:

var myViewModel = function() {
    var self = this;
    console.log('My viewModel');
    console.log(self);
}(); // <--

This makes the function execute immediately and return undefined to myViewModel, which you can easily verify by adding a console.log statement inside and after the function.

I guess you want to omit those and assign the function itself to myViewModel:

var myViewModel = function() {
    var self = this;
    console.log('My viewModel');
    console.log(self);
}; // <--

Learn more about this.

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072