Javascript: problem with 'this'

Here is a snippet of code

function test() {
    this.value = "foo";       
}

$(document).ready(function () {
    test();
    alert(this.value);   //--> return undefined
    alert(window.value); //--> return 'foo'
});

Can someone explain these results to me?

Hi

Salvatore

+3
source share
5 answers

In your function test(), thisrefers toDOMWindow

The $(document).ready()function thismeant document.

So, since in test()you set the window value, therefore window.value ==> 'foo', butdocument.value ==> undefined

Read this article on a feature area that might help.

+6
source

this - This is a difficult keyword to get your head around.

I advise you to read this, this may help a little more http://www.quirksmode.org/js/this.html

: , this.value . jQuery document.ready(..).

+1
function test() 
{ 
      this.value = "foo"; // this is window
}

 $(document).ready(function () {
    test();
    alert(this.value);   //--> this is window.document
    alert(window.value); //--> return 'foo'
});
0

jquery, :

 $(document).ready(...)

, onReady . ( ).

onReady,

 alert(this.value);   //--> return undefined

return undefined, .

test();

, , javascript , .

, , , , , ( javascript ), , , ,

alert(window.value); //--> return 'foo'

?

( ) window, value window.

,

0

All Articles