Javascript confusion....

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • George Ter-Saakov

    Javascript confusion....

    I am trying to get into depth of JavaScript a little more and find it a bit
    confusing for person who is used to C#/C++ object oriented approach..

    So I need some help in understanding how staff works... Given following
    object definition

    ZColor = function(num)
    {
    var a = num + 1;
    this.b = num + 2;
    this.show = function()
    {
    alert(a);
    alert(this.b);
    }
    }



    I have folowing code that runs when htm page is loaded.

    var obj = new ZColor(6);
    setInterval(obj .show, 1000);

    So it produces 2 alerts. First is "7" and second is "undefined"
    So basically show method has access to "a" variable and does not have access
    to "b" variable...

    I do understand why "alert(this .b)" does not work from timer function. Cause
    timer has not idea that i want to run it under "obj" as "this" scope.

    But what puzles me is why "alert(a)" works... .

    Thanks
    George.



  • Anthony Jones

    #2
    Re: Javascript confusion....

    "George Ter-Saakov" <gt-nsp@cardone.com wrote in message
    news:eHxnqB8fIH A.4196@TK2MSFTN GP04.phx.gbl...
    Thanks, I did not have exposure to any of those languages "ruby,
    python,.."
    So that thing is quite new for me.
    >
    The parallel you made between closure and delegates does help although it
    seems to me the "closure" is much "bigger" in terms of functionality.
    On the other hand I do not see much use of it (right now) except imitating
    delegates :)
    >

    One use is to solve the 'this' problem you identified:-

    ZColor = function(num)
    {
    var a = num + 1;
    this.b = num + 2;
    this.show = function()
    {
    alert(a);
    alert(this.b);
    }
    }

    function setInterval3(fn , period, target)
    {
    setInterval(fun ction() {fn.call(target )}, period)
    }

    var obj = new ZColor(6);
    setInterval3(ob j.show, 1000, obj);

    In this case the alert(this.b) will now work


    --
    Anthony Jones - MVP ASP/ASP.NET


    Comment

    Working...