开发者

Javascript : problem with 'this'

开发者 https://www.devze.com 2023-03-03 23:02 出处:网络
Here is a piece of code function test() { this.value = \"foo\"; } $(document).ready(functio开发者_如何学Pythonn () {

Here is a piece of code

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

$(document).ready(functio开发者_如何学Pythonn () {
    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.


Javascript's this works differently according to how the function is called.

Rather than explaining it all myself, I'll point you to this article, which covers it in excellent detail: http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this


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

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


I'm not used to jquery but the solution should be simple:

 $(document).ready(...)

attach the function used as parameter to the event onReady of the document object. The context of the function should be the document or the event (depends on the framework you use).

We can analize the onReady function body starting from the line

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

return undefined as the element pointed from this does not have that properties.

The trick lies into the line

test();

You may think that the this keyword into the test function body refers to the context of the outer function but javascript is lexycally scoped and the context of a function is defined at the time the function is declared instead that at the time of the function is called.

Saying that you can think that the function is a global one and then the this keyword it address is the function itself (in javascript a function is an object too) and then how is it that test pollute the window object as clearly indicate by the line

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

?

When you call a function (not a method or a constructor) or a it behaves as it is a method of the window object and then in the test function you are defining the value property of the window object.

The complete picture is a bit more complex but theese are the basics

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号