Skip to content

OutputNot attempted

The self = this pattern

const b = {
name: 'Vivek',
f: function () {
var self = this;
console.log('1', this.name);
(function () {
console.log('3', self.name);
console.log('2', this.name);
})();
},
};
b.f();

Spaces and quote style don’t matter · write a thrown error as TypeError

Ctrl Enter
Show answer & explanation

The expected output comes from actually running the snippet; opening this shows it next to the explanation.

Inside f (called as b.f()) this is b. The IIFE is a plain call, so in strict mode its this is undefined and this.name throws TypeError. self captured b in a closure, which is how code worked before arrow functions.