In your example, "this" should be obj, as some commentators have noted. Here are the details that explain why -
In Javascript, the value of "this" changes depending on how you call the function:
- When a function is stored as a property of an object and you call this function by calling obj.foo (), "this" will be obj.
Example:
var obj = { x: 1, increment: function() { this.x = this.x + 1; }; obj.increment();
- When you call a function using syntax that does not apply to any native object, this will be a global environment.
Example:
function someFunc(a, b) { return a + b;
- When you call a function as if it were a constructor using a new operator, a new object will be created for you, and "this" will point to this new object.
Example:
function SomeConstructor() { this.x = 42;
// the result will be {x: 42}
- When you use call () or apply (), you can control what "this" is.
(There is no example, since it is quite far from your question. See the docs for apply () or call () for an example.)
source share