I have a program as :
$(document).ready(function() {
this.name = "John";
var someFunc = function()
{
return this.name;
}
});
From my understanding , the value of 'this' in someFunc is "window" since it is not contained in any object.
My question is why is the value of 'this' is 'HtmlDocument' in $(document).ready(function() { alert(this) }?
And since someFunc is under $(document).ready function why cant its value not be 'HtmlDocument' as well ?
Whats exactly happening behind the scene which is causing the value of this to be different in different cases?
The variable this has a concept of scope in JavaScript, its value depends on where you're accessing to it, I'd try to explain this with an example, see following code snippet:
$("#document").ready(function() {
console.log("HERE 'this' references to its owner object \"HTMLDocument\"");
console.log(this.toString());
jsFunction();
$("#test").jqueryFunction();
console.log("You could call jsFunction on window:");
window.jsFunction();
console.log("But you can't call jqueryFunction on window:");
try{
window.jqueryFunction();
}catch(err){console.log("error");}
console.log("Neither you could call jsFunction on \"div test\":");
try{
$("#test").jsFunction();
}catch(err){console.log("error");}
//Inner functions
console.log("The same thing applies to inner functions");
var innerFunc = function(){
console.log(this.toString());
var moreInnerFunc = function(){
console.log(this.toString());
}
moreInnerFunc();
}
innerFunc();
(function(){
console.log("Immediately-Invoked Function Expression (IIFE)");
console.log(this.toString());
})();
var extDeclared = externallyDeclared;
extDeclared();
$("#document").extDeclared();
});
function jsFunction(){
console.log("HERE 'this' references to its owner \"window\"");
console.log(this.toString());
}
(function( $ ){
$.fn.jqueryFunction = function() {
console.log("HERE 'this' references to its owner \"div test\"");
console.log($(this).prop("id"));
};
})( jQuery );
function externallyDeclared(){
console.log("externallyDeclared may be window or its other owner");
console.log(this.toString());
}
(function( $ ){
$.fn.extDeclared = externallyDeclared;
})( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" />
As you can see, this references always to its "owner" object, so when you declare a function outside any kind of object, its owner is the window object, otherwise it references to the object where the function is defined.
In summary:
function externallyDeclared(){
console.log("externallyDeclared may be window or its other owner");
console.log(this.toString());
}
(function( $ ){
$.fn.extDeclared = externallyDeclared;
})( jQuery );
$("document").ready(function(){
var extDeclared = externallyDeclared;
extDeclared(); //<-- "no owner" - this=window
$("#document").extDeclared(); //<-- "has an owner" - this=its owner
});
I hope I was clear, bye.