Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : problem with 'this'

Tags:

javascript

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

like image 305
Salvatore DI DIO Avatar asked May 19 '26 20:05

Salvatore DI DIO


2 Answers

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

like image 176
Naftali Avatar answered May 22 '26 10:05

Naftali


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.

like image 44
James Avatar answered May 22 '26 08:05

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!