Akash
Akash

Reputation: 5012

Access javascript vars within a inline function

I wish to access a variable named storedata while dynamically changing the objects event onclick event handler

function update_data(storedata)
{
    obj.onclick=function() {remover(this,storedata); };
}

Not able to access storedata within the inner function.

When I try using alert(obj.onclick) the result comes out to be remover(this,storedata). It seems the variable is not been replaced by its value!!

Any Ideas?

Upvotes: 1

Views: 67

Answers (2)

YMMD
YMMD

Reputation: 3780

You need to attach it as a property of the object which has got the event handler anyhow. When you storedata is a string and you are using HTML5, you could for example accomplish it that way:

function update_data(storedata){
   obj.dataStoredata = storedata;
   obj.onclick = function(){
      remover(this);
    };
}

Inside of your remover function them you can simply access this.dataStoredata which will contain your data.

Upvotes: 0

Quentin
Quentin

Reputation: 943547

It is "replaced". The problem is just the way you are trying to inspect it.

When you alert a function, you get a stringified version of the function … and that includes the variable names and not serialisations of every variable.

If you were to actually call the function, the variable would be available with the value you gave it.

Upvotes: 2

Related Questions