2013-09-11 26 views
0

考虑以下几点:JavaScript构造使用问题活动

// 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在那里你看到上面rT(py, 'click', pl.z)执行,并rT(he, 'mouseout', ns)不会改变pl.nfunction eO在其内部的mouseout事件执行? rT(py, 'click', pl.z)是否应该重新分配构造函数n属性?请帮我理解为什么这不起作用,就像我以前用过的全球var一样。

回答

0

当您拨打funA时,它不知道该用什么作为它的this值。你可以通过一个绑定函数来解决这个问题:

rT(py, 'click', pl.z.bind(pl)) 
+0

谢谢。为了向后兼容,我现在使用'call'传递一个上下文参数。 – PHPglue