this
keyword behaves somewhat differently in the context of the difference.
Global context
In the global execution context (outside of any function), this refers to the global object, whether in strict mode or not.
Functional context
Inside a function, the meaning of this depends on how the function is called.
Simple challenge
function foo() { console.log(this) }
In non-line mode, this
will default to a global object.
In strict mode, this
will default to undefined.
call
or apply
function foo() { console.log(this) } var o = {'name': 'test object'}; foo.call(o)
this
can be bound to a specific object in a call using call or apply methods.
bind
bind
method returns a function that uses the special bind
object as the this
object in the function.
function foo() { console.log(this) } var o = {'name': 'test object'}; bar = foo.bind(o) bar()
Refer to this link for more information: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this
To explain
in this case obj.foo();
this
foo
function is obj
, so this.a
refers to obj.a
in this case setTimeout( obj.foo, 100 );
obj.too
is a reference to the foo
function. setTimeout
will execute it in a global context.
in this case setTimeout( obj.foo.bind(obj), 100 );
, obj.foo.bind(obj)
returns a reference to a function that associates this
with obj
. setTimeout
will execute it in obj
context