We've seen in the previous post that this
is bound depending on where is called, if you haven't read it please go back to
Understanding how `this` works in Javascript - The call-site
Kevin J. Estevez ・ Mar 18 '19
I'll start by saying that default binding is the last case which is going to match in case any other fit.
When default binding is applied, the global object will be bind to the called function, consider the next code:
function foo() {
console.log(this.a);
}
function bar() {
function bazz() {
console.log(this.b);
}
bazz();
}
var a = 3;
var b = 5;
foo(); // 2
bar(); // 5
It is worth to point out that global object will be eligible just if strict mode
is not set either inside or outside the definition scope of the called function, but if 'use strict'
is set at one of them, then this = undefined
.
'use strict'
inside function's definition
function foo() {
'use strict';
console.log(this.a);
}
var a = 3;
foo(); // TypeError: Cannot read property 'a' of undefined (this = undefined)
'use strict'
outside function's definition
function bar() {
'use strict';
function bazz() {
console.log(this.b);
}
bazz();
}
var b = 5;
bar(); // TypeError: Cannot read property 'b' of undefined (this = undefined)
It's worth to point out, despite of biding is entirely based on call-site, the 'use strict'
concern is totally base on where the function itself is declared.
function foo() {
console.log(this.a);
}
var a = 3;
(function(){
'use strict';
foo(); // 3
})();
Top comments (0)