日期:2014-05-16  浏览次数:20373 次

js一个很奇怪的问题

?

前几天在javaeye上看到一篇帖子:JS优化系列】从一个计时器的写法探讨js多种实现方式的优劣,感觉楼主确实厉害,一个计时器能有那么多优雅的写法,而且全部是用的面向对象的思想,我花了整整一天时间把那些写法全部消化,也看了那些留下的评论,发现javaeye上面确实人才辈出,难怪我师兄把博客都从csdn搬到javaeye了。这里我把我发现的一个很奇怪的问题贴出来,希望有大牛能帮我解惑哈

帖子里的“代码六”是这样的:

?

function Timer(id){  
    this.id = id;  
    this.timer = null;  
    this.count = 0;  
}  
Timer.prototype = {  
    begin : function(count){  
        this.count = count;  
        this.show(this)();//注意这里不是Timer.show(this)();  
        this.timer = setInterval(this.show(this),1000);//注意这里不是Timer.show(this)();  
    },  
    show : function(obj){     
        return function(){  
            if(obj.count < 0){  
                document.getElementById(obj.id).innerHTML = "over";  
                clearInterval(obj.timer);  
                return ;  
            }  
            document.getElementById(obj.id).innerHTML = obj.count;  
            obj.count--;  
        }  
    }   
}  

?

这份代码没有任何问题,运行结果一切正常,可是,当我把“Timer.prototype={”这一行以及后面的移到Timer构造函数内部的时候,却发现在firebug下面提示:“t1.begin is not a function”这样的错误,代码如下:

?

<body>  
<div id="time1">time1</div>  
<div id="time2">time2</div>  
</body>  
<script>  
function Timer(id){  
    this.id = id;  
    this.timer = null;  
    this.count = 0;  
	Timer.prototype = {
		begin : function(count){  
			//alert(this);
			this.count = count;  
			this.show(this)();//注意这里不是Timer.show(this)();  
			this.timer = setInterval(this.show(this),1000);//注意这里不是Timer.show(this)();  
		},  
		show : function(obj){     
			return function(){  
				if(obj.count < 0){  
					document.getElementById(obj.id).innerHTML = "over";  
					clearInterval(obj.timer);  
					return ;  
				}  
				document.getElementById(obj.id).innerHTML = obj.count;  
				obj.count--;  
			}  
		}  
	};
}

		
t1 = new Timer("time1");  
t2 = new Timer("time2");

t1.begin(10);  
t2.begin(10);  
</script>

?而且,看到“代码七”就发现,都用Timer.prototype.beginTimer.prototype.show就算写在里面也能运行:

function Timer(id){  
    this.id = id;  
    this.timer = null;  
    this.count = 0;  
    Timer.prototype.begin = function(count){  
        this.count = count;  
        this.show(this)();//主要这里不是Timer.show(this)();  
        this.timer = setInterval(this.show(this),1000);//主要这里不是Timer.show(this)();  
    }  
    Timer.prototype.show = function(obj){     
        return function(){  
            if(obj.count < 0){  
                document.getElementById(obj.id).innerHTML = "over";  
                clearInterval(obj.timer);  
                return ;  
            }  
            document.getElementById(obj.id).innerHTML = obj.count;  
            obj.count--;  
        }  
    }   
}  
?我不明白为什么会这么诡异,希望俺帖能起到抛砖引玉的效果。期待大牛们的精彩解答!

?

?

?