使用事件的JavaScript构造函数问题
考虑以下几点:使用事件的JavaScript构造函数问题,javascript,constructor,Javascript,Constructor,考虑以下几点: // 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
// 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
发生了变化
那么,如果在上面看到的
rT(py,'click',pl.z)
的位置执行pl.z
,那么rT(he,'mouseout',ns)
在mouseout
事件上执行的函数eO中没有更改pl.n
?rT(py,'click',pl.z)
是否应该重新分配构造函数n
属性?请帮助我理解为什么它不像我过去使用的全局var
那样工作。当你调用funA
时,它不知道该用什么作为它的这个
值。您可以传递一个绑定函数来修复:
rT(py, 'click', pl.z.bind(pl))
非常感谢。为了向后兼容,我现在使用call
传递一个上下文参数。