Jaeeun Lee Jaeeun Lee - 3 months ago 9
Javascript Question

JavaScript "this" in a function block

this
refers to the object it belongs to, for example:

var someObj = {
logObj : function() { return this }
}

obj.logObj() => someObj


and a function is an object. But then why does
this
in a function refer to the window, not the function? For example,

function someFunc() { return this }


won't
return someFunc()
, but
window
.

Answer

It's true, a function is an object. However, the statements inside the function are not called with this set to the function itself. That would keep this from referencing the object that it was called on, and therefore eliminate much of the usefulness of this. There are ways to accomplish what you seek though.

"When a function is called as a method of an object, the object is passed to the function as its this value." ECMAScript Specification 4.3.31

Functions are not called as methods of themselves. Functions not executed as methods of an object are called as methods of the global object (or undefined if in "strict" mode).

function test() { 
  console.log(this == window);
}

var obj = {'test': test};

test();
window.test();
obj.test();

If you really want for the this in a function to refer to itself, then you will have to add the function as a property of itself, or use a function such as apply, call, or bind which have a thisArg.

function test() { console.log(this) };

test.test = test;

test.test();
test.call(test);
test.apply(test);
test.bind(test)();

Comments