0

考虑以下:

// Constructor calls Function and assigns value to n
function zo(f1, f2){
  this.n = 0;
  this.z = function(){
    if(this.n === 0){
      f1(); this.n = 1;
    }
    else{
      f2(); this.n = 0; 
    }
  }
}

// Event Function makes sure it's the correct target
function rT(elA, evt, funA){
  for(var i in elA){
    (function(i){
      var te = elA[i];
      te['on'+evt] = function(ev){
        var e = ev || event;
        var rt = e.relatedTarget;
        while(rt && rt !== te){
          rt = rt.parentNode;
        }
        if(rt !== te){
          if(funA[0]){
            funA[i]();
          }
          else{
            funA();
          }
        }
      }
    })(i);
  }
}

var pl = new zo(function(){console.log('fun1')}, function(){console.log('fun2')});

// bg[number] is "url('differentBackgrounds.png')"
// lpbS and so on is lpb.style - yes that works
function eI(){
  ttcS.display = lpbS.display = cncS.display = bk;
}

// pay attention to this function
function eO(){
  if(pl.n === 1)ttcS.display = lpbS.display = cncS.display = nn;
}

function pI(){
  lpbS.background = bg[2]; pbS.background = bg[14];
}
function pO(){
  lpbS.background = bg[1]; pbS.background = bg[13];
}
function mI(){
  mtS.background = bg[17];
}
function mO(){
  mtS.background = bg[16];
}
function fI(){
  fsS.background = bg[28];
}
function fO(){
  fsS.background = bg[27];
}
var he = [e, pst, vdo, ttc, lpb,pb, mt, fs]; // elements I assigned to vars
var hs = [eI, pI, pI, pI, pI, pI, mI, fI]; // functions mouseEnter
var ns = [eO, pO, pO, pO, pO, pO, mO, fO]; // functions mouseLeave

rT(he, 'mouseover', hs);

// watch this function
rT(he, 'mouseout', ns);

// watch this function
rT(py, 'click', pl.z);

这就是问题所在。如果我这样做,

console.log(pl.n); pl.z(); console.log(pl.n); pl.z(); console.log(pl.n);

你可以看到pl.n变化。

那么,如果在上面pl.z看到的地方执行,为什么在事件中执行的my 内部没有改变?不应该重新分配 Constructors属性吗?请帮助我理解为什么这不像 global 那样工作,我过去确实使用它来完成这项工作。rT(py, 'click', pl.z)rT(he, 'mouseout', ns)pl.nfunction eOmouseoutrT(py, 'click', pl.z)nvar

4

1 回答 1

0

当您调用 时funA,它不再知道将什么用作其this值。您可以传递一个绑定函数来解决这个问题:

rT(py, 'click', pl.z.bind(pl))
于 2013-09-11T02:02:28.253 回答