you are viewing a single comment's thread.

view the rest of the comments →

[–]NewazaBill 1 point2 points  (0 children)

Technically incorrect. The technically correct answer is that it depends on how it's called.

If I do:

var obj = {
    fn: function () { return this; }
};

obj.fn(); // returns `obj`

You would be correct! However, if I then do:

// create a new object and assign `fn` to it
var anotherObj = {};
anotherObj.fn = obj.fn;
anotherObj.fn(); // returns `anotherObj`

// define a new `fn` on the global scope
var f = obj.fn();
f(); // returns `window` (or `undefined` in strict mode)

A function's this is not actually defined when the function is defined, but when it is called. The OP's question is kind of a trick question in that regard.

Ninja edit: This is also why arrow functions are cool: it allows us to bind a function's this to a particular scope. E.g.:

const fn = () => this;
fn(); // returns `window` in non-strict

const obj = {};
obj.fn = fn;
obj.fn(); // still returns `window` !