*this* become local variable in functions
After compilation I noticed some of the functions context this have be replaced with local variable this$1.
Can someone explain why is it like that ?
Why it happening only in some of the functions ?
Is there anything wrong in my code ?
The code:
export let Prototypes = {
getAdContainer: function() {
return this.adContainer;
},
getSize: function() {
return {
width: this.width,
height: this.height
}
},
addEventListener: function(event, callback) {
if (!this.events.hasOwnProperty(event)) {
return;
}
this.events[event].push(callback);
},
removeEventListener: function(event, callback) {
if (this.events.hasOwnProperty(event)) {
return;
}
for (var i = 0; i < this.events[event].length; i++) {
if (this.events[event][i] === callback) {
this.events[event].splice(i, 1);
}
}
}
}
Compiled code:
var Prototypes = {
getAdContainer: function() {
return this.adContainer;
},
getSize: function() {
return {
width: this.width,
height: this.height
}
},
addEventListener: function(event, callback) {
if (!this.events.hasOwnProperty(event)) {
return;
}
this.events[event].push(callback);
},
removeEventListener: function(event, callback) {
var this$1 = this;
if (this.events.hasOwnProperty(event)) {
return;
}
for (var i = 0; i < this.events[event].length; i++) {
if (this$1.events[event][i] === callback) {
this$1.events[event].splice(i, 1);
}
}
}
}
you can see in compiled code, the removeEventListener
introduced var this$1 = this; and replaced all its this to this$1
I figured it out that its only happening when im using ** for loops** in a function. and I have many functions with many for loops which means many extra variables.
BTW I'm using gobble
with rollup
js api and buble
plugin for compiling