please bring closure to my problem

J

jman

here's my function

MyApp.prototype.showAddress = function()
{
this.instance_var = 10;

this.somefunction( function()
{
alert(this.instance_var);
});
}

inside the function, i can't seem to access this.instance_var

- i.e. 'this' is undefined.

w/o passing it to the inline function - how can i access the this
object.
 
D

David Mark

here's my function

MyApp.prototype.showAddress = function()
{
     this.instance_var = 10;

        this.somefunction( function()
        {
              alert(this.instance_var);
        });

}

That is an odd method.
inside the function, i can't seem to access this.instance_var

- i.e. 'this' is undefined.

The "this" identifier is never undefined.
w/o passing it to the inline function - how can i access the this
object.

I can assume that the this.somefunction method calls the function
passed to it, in which case, "this" will reference the global object.
You can work around this by setting a local variable to reference the
MyApp object:

MyApp.prototype.showAddress = function()
{
this.instance_var = 10;
var that = this;

this.somefunction( function()
{
alert(that.instance_var);
});

};
 
J

jman

i edited the snippet to show just the
relevant parts.

actually this.somefunction is an event
callback function.

this.somefunction( "click", function () { /* this var is undefined
here */ } }

your solution worked - thanks.
 
B

Bruno Desthuilliers

jman a écrit :
i edited the snippet to show just the
relevant parts.

actually this.somefunction is an event
callback function.

this.somefunction( "click", function () { /* this var is undefined
here */ } }
As David told you, 'this' is never undefined. Now what it refers to at
call time is higly context-dependent, and is probably one of the most
important things to learn if you hope to get javascript right.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Closure 3
Building my own friend 4
Help with my navigation, please 0
Why is this a closure? 2
Please fix my code 1
Please help me to solve this JS problem 6
Closure bug 67
Help please 8

Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,825
Members
47,371
Latest member
Brkaa

Latest Threads

Top