The value of 'this' inside a function
I have a program like:
$(document).ready(function() {
this.name = "John";
var someFunc = function()
{
return this.name;
}
});
In my opinion, the value of this ' in someFunc
is "window" since it is not contained in any object.
My question is, why is the value < this
'is' HtmlDocument
' in $(document).ready(function() { alert(this) }
?
And since it someFunc
is under the $(document).ready
function, why is its value not equal to ' HtmlDocument
'? What exactly is going on behind the scenes that makes the meaning of this different in different cases?
source to share
A variable this
has a concept of scope in JavaScript, its meaning depends on what you are accessing it, I will try to explain it with an example, see the 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, it this
always refers to its "owner" object, so when you declare a function outside of any object, the object is the owner window
, otherwise it refers to the object in which the function is defined.
In short:
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
});
Hope I was simple for now.
source to share