As I delve into a book, it mentions that this
within a function can be established in four different ways: default, implicit, explicit binding, and through the use of the new
syntax. Regardless of the method, this
is determined at the time of the function call. Let's examine an example.
Upon invoking jajca()
, one would anticipate this
to be set via default binding, meaning when jajca()
is called, this
should already reference the object created using the new
syntax. However, perplexingly, I noticed that within jajca
, this
actually points to the window object instead of the expected object created with new
.
function jajca() {
this.musicFolderPath = "value2"; // remains unassigned to the correct this.musicFolderPath
}
function Music(){
this.musicFolderPath;
jajca(); // music.musicFolderPath is undefined
// jajca.call(this); music.musicFolderPath is set correctly
}
var music = new Music();
//music.musicFolderPath remains undefined
Why isn't this
being set as anticipated? It appears that when explicit binding is utilized, this
does indeed refer to the object created with the new
keyword as expected.