Here is a piece of code
function test() {
this.value = "foo";
}
$(document).ready(function () {
test();
alert(this.value); //--> return undefined
alert(window.value); //--> return 'foo'
});
Can someone explain me those results ?
Regards
Salvatore
In your function test(), this is refferring to the DOMWindow
In the $(document).ready() function, this was referring to document.
So since in test() you set the window's value, that is why window.value ==> 'foo', but document.value ==> undefined
Read this article on function scope which might help
this is a complicated keyword to get your head around.
I advise reading through this, it may help a bit more http://www.quirksmode.org/js/this.html
Edit: I also believe that your this.value problem is caused because of scoping. Your function has an entirely different scope to your jQuery document.ready(..) one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With