Click here to Skip to main content
15,887,875 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I am beginner to javascript.

JavaScript
    var ButtonHandler = function()
    {
        var me = this;
        
        this.click = function()
        {
            alert("Click");
            me.meClick(); // How It can find "me"!!?
        };
        this.meClick = function()
        {
            alert("meClick");
        };
    }; 
    var b = new ButtonHandler(); // me created and destroyed.

    function onBtnclick()
    {
        b.click();
        //ButtonHandler.prototype.click();
    }
}


I bind onBtnclick to button click.

My confusion is at creation of var b "me" is created and destroyed.

but when i click button,How it finds "me"?.


Sorry for my english
Thanks all.
Posted
Updated 9-Jul-12 2:30am
v2
Comments
[no name] 9-Jul-12 8:25am    
I am not sure what your confusion is. me is declared in the ButtonHandler so that is how this.click finds it....
Bhavin Jagad 9-Jul-12 8:29am    
Thanks for the view,
when i declare "var me", is it considered as member variable? or its a local variable?

armagedescu 9-Jul-12 8:45am    
It is member variable and private.
Manfred Rudolf Bihy 9-Jul-12 8:51am    
It is a local variable allright, but the function is being defined in the environment where that variable is also defined and is thus preserverd for use by the function. See my solution for the details.
Bhavin Jagad 9-Jul-12 9:14am    
Thanks for the solution,Manfred

This is what is called a closure[^] in computer science. As the function is being defined that is being assigned to this.click all the variables that are defined in the surrounding environment are reachabel from within that function definition.

Seeh here: http://www.javascriptkit.com/javatutors/closures.shtml[^]

— Manfred
 
Share this answer
 
Comments
Sandeep Mewara 13-Jul-12 3:26am    
My 5!

Didn't knew the word 'closure' for it. Thanks for sharing. :)
at creation of var b "me" is created and destroyed.
When and where did 'me' was destroyed?

As long as 'b' is available, object exists and so does it's members. Right? me was not destroyed and so it exists.
 
Share this answer
 
Comments
Prasad_Kulkarni 10-Jul-12 6:37am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900