2
function Cons(name) {
var pvar1="hi "+name;
sayhi = function() {
   alert(pvar1);
}
attEvents(){
$('#'+name).bind("click",sayhi);
}
}
var a = new Cons('name1');
var b = new Cons('name2');
var c = new Cons('name3');

Let us assume that name1, name2, name3 are all divs. Now, whatever div I click, I am always getting "hi name3". The private variable is having the last stored value in it irrespective of the div clicked. Any help is appreciated.

Thanks

2
  • Probably because sayhi is global and .bind("click",sayhi); is called some time after the three objects have been created. But to know for sure you would have to correct/clarify this statement: attEvents(){ $('#'+name).bind("click",sayhi);} What is it doing? Commented Mar 20, 2012 at 10:42
  • My mistake, attEvents will just attach the events to the div. It will be called at the end of Cons(). And yes sayhi was in global scope. Thanks for the help. Did not know that var should be used even when functions are defined. Thanks a lot :) Commented Mar 20, 2012 at 11:02

1 Answer 1

2
sayhi = function() {
   alert(pvar1);
}

If you define it without var keyword then it is defined as a global. Thus sayhi refers to the function defined as a last one. Use

var sayhi = function() {
   alert(pvar1);
}

or

var pvar1 = "hi "+name,
    sayhi = function() {
        alert(pvar1);
    };

Note the comma. Or true jQuery style

$('#'+name).bind("click", function() {
    alert(pvar1);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.