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

作用域的问题
本想显示出不同函数的名称
但显示的结果却是相同的
属性定义是全局的?
如何定义自作用于该类的属性?


------------------------------

<!DOCTYPE   html   PUBLIC   "-//W3C//DTD   XHTML   1.0   Transitional//EN "   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html   xmlns= "http://www.w3.org/1999/xhtml ">
<meta   http-equiv= "Content-Type "   content= "text/html;   charset=utf-8 "   />
<title> test </title>
</head>
<body>

<fieldset>
<legend> a </legend>
<p   id= "a1 "> </p>
</fieldset>
<fieldset>
<legend> b </legend>
<p   id= "b1 "> </p>
</fieldset>

<script   language= "javascript ">
function   $(s){
return   document.getElementById(s);
}

function   a()   {
this.name   =   "a ";
setInterval(   'time1(this) ',   1000   );
}
function   time1(o){
var   d   =   new   Date();
$( "a1 ").innerHTML   =   "(a)   :   "   +   o.name   +   "   -   "   +   d.getSeconds();
}

function   b()   {
this.name   =   "b ";
setInterval(   'time2(this) ',   1000   );
}
function   time2(o){
var   d   =   new   Date();
$( "b1 ").innerHTML   =   "(b)   :   "   +   o.name   +   "   -   "   +   d.getSeconds();
}

var   at   =   a();
var   bt   =   b();
</script>

</body>
</html>

------解决方案--------------------
var at = a();
var bt = b();
==》
var at = new a();
var bt = new b();

既然你已经使用了 this 这样的类写法,那你调用类的时候就应该用 new 来新开实例!
------解决方案--------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns= "http://www.w3.org/1999/xhtml ">
<meta http-equiv= "Content-Type " content= "text/html; charset=utf-8 " />
<title> test </title>
</head>
<body>

<fieldset>
<legend> a </legend>
<p id= "a1 "> </p>
</fieldset>
<fieldset>
<legend> b </legend>
<p id= "b1 "> </p>
</fieldset>

<script language= "javascript ">
function $(s){
return document.getElementById(s);
}

function a() {
this.name = "a ";
var me = this;
setInterval( function(){time1(me)}, 1000 );
}
function time1(o){
var d = new Date();
$( "a1 ").innerHTML = "(a) : " + o.name + " - " + d.getSeconds();
}

function b() {
this.name = "b ";
var me = this;
setInterval( function(){time2(me)}, 1000 );
}
function time2(o){
var d = new Date();
$( "b1 ").innerHTML = "(b) : " + o.name + "