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
.