I've found the solution!
Here is a clearer piece of code that shows the issue:
Code:
<!--
cliccando il link che contiene l'immagine, cambiera' il src (visualizzandolo) ma per un tempo brevissimo, per poi tornare al src originale.
Qualcuno mi spiega questo comportamento? Cosa sbaglio?
-->
<html>
<head>
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script>
var ob1= new Object();
var ob2= new Object();
function functionToCall(obj, methodName){
var f= function(){
return(obj[methodName]());
}
return(f);
}
function ScopeChainTry(nameObj){
var nrCall= 0;
var f= function(){
document.write("<br>" + nrCall++);
}
if(ScopeChainTry.prototype.fun == undefined){
ScopeChainTry.prototype.fun= f;
}
window[nameObj].actionFun= functionToCall(this,"fun");
}
var a= new ScopeChainTry("ob1");
ob1.actionFun();
ob1.actionFun();
var b= new ScopeChainTry("ob2");
ob2.actionFun();
ob1.actionFun();
</script>
</head>
<body>
<script>
</script>
</body>
</html>
Well, you were right, it is the same variable of course! But I was wondering why.
The reason is simple: the scopechain related to the function referenced by ScopeChainTry.prototype.fun will be always the same (that function will have a scopechain bind to the execution context of the first "new ScopeChainTry"). That's it
A solution could be like this (I use the object that the constructor initializes to store variables, not the function object itself):
Code:
<!--
-->
<html>
<head>
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script>
function associateObjWithEvent(object, methodName){
var fun= function(e){
return(object[methodName](e, this));
}
return fun;
}
function DHtmlObject(elementID){
var el= document.all[elementID];
this.nrClick= 0;
var f= function(event, element){
element.value="click " + this.nrClick++;
};
if(! DHtmlObject.prototype.doOnClick)
DHtmlObject.prototype.doOnClick= f;
if(el){
el.onclick= associateObjWithEvent(this, "doOnClick");
}
}
</script>
</head>
<body>
<form>
<input id="try1" type="button" value="try me">
<input id="try2" type="button" value="try me">
</form>
<script>
var a= new DHtmlObject("try1");
var b= new DHtmlObject("try2");
</script>
</a>
</body>
</html>