Understanding "this" within anonymous function in JavaScript -
in post, lots of answers there discussing this
keyword in javascript. however, still confuse this
in anonymous function
following
// mymodule.js 'use strict'; (function(handler) { // export methods handler.b = b; handler.a = a; function a() { console.log(this); console.log('function invoked...'); } function b() { console.log(this); console.log('function b invoked...'); try { a(); this.a(); } catch (err) { console.log('exception ' + err); } } })(module.exports); // test.js var mymodule = require('mymodule.js'); mymodule.b();
output: (running under node.js)
{ b: [function: b], a: [function: a] } function b invoked... undefined function invoked... { b: [function: b], a: [function: a] } function invoked...
the output indicates function a
in 2 different scopes. right? why there 2 scopes function a
?
as know, this
related scope. , this
in anonymous function of mymodule
undefined
. according output, 1 of scope of function a
undefined
, other { b: [function: b], a: [function: a] }
. difference between them?
this
, scope have nothing each other. in javascript, this
set how function called, not it's defined. (there 2 exceptions rule, i'll mention them below.)
so when you're calling a
, you're setting this
during call (largely implicitly). when this:
a();
...you're calling a
without doing explicit set this
should be; result, you're implicitly calling this
set undefined
, because code in strict mode. (if in loose mode, you'd calling this
set reference global object.) it's worth noting you're resolving identifier a
via context created call anonymous function, contains a
, b
(effectively) variables.
but here:
this.a();
...you're calling a
part of expression getting function reference object property (a
; note different meaning a
, both property , context variable refer same function). act of doing calls a
this
set reference object got property from.
that's why see 2 different values this
in a
.
the exceptions "this
set how call it" rule are:
es6's "arrow" functions, inherit
this
context (not scope) they're created.es5's "bound" functions (the result of calling
.bind
on function reference), havethis
baked them.bind
call , see same valuethis
.
Comments
Post a Comment