当前位置: 代码迷 >> JavaScript >> 关于 javascript 的 面向对象 有关问题 糊涂
  详细解决方案

关于 javascript 的 面向对象 有关问题 糊涂

热度:976   发布时间:2012-03-13 11:21:10.0
关于 javascript 的 面向对象 问题 糊涂
function   A   =   function(){
    this.X()  
}


A.prototype   =   {

  X:function(){    
        this.Y();  
        /-----------------------
        var   Timer   =   setIntervarl(function(){
              this.Z();
        },100);
        /*---------------------
    },
  Y:function(){},
  Z:function(){}  

}

this.X(),this.Y()   this都是A
为什么   this.Z()   的   this   是   window     希望是A
跟计时器的用法有关么
怎么解决   有什么解决方法   多谢   望指教

这个写法好不好   另怎么个写法   最好都封装住   让方法能访问所有的类内部变量(不用定义全局的)


------解决方案--------------------
<SCRIPT LANGUAGE= "JavaScript ">
<!--
var A = function(){
this.X()
}


A.prototype = {

X:function(){
this.Y();
var th = this;
var Timer = setInterval(function(){th.Z();},1000);
},
Y:function(){},
Z:function(){alert( "z run ");}

}
var a = new A();
//-->
</SCRIPT>
------解决方案--------------------
function A = function(){
this.X()
...
...
}
//也可以把你要实现的A的功能都写在里边,当作一个对象的方法来调用

为什么 this.Z() 的 this 是 window 希望是A
//不用this可否??

A.prototype =
//这种用法我在一些老外的网站上经常见,可能是习惯问题,自己喜欢就好了
------解决方案--------------------
function A{

A.prototype.X = function(){}
A.prototype.Y = function(){}

}
============================
function A()
{
this.X=function(){alert( 'class A:fun_X() ');};
this.Y=function(){alert( 'class A:fun_Y() ');};
}
var a=new A();
a.X();
a.Y();

这么写有两个相关问题:1.对象的公用方法 2.闭包
你去查查资料看吧
------解决方案--------------------
function A(){
this.a = '2121 ';
var b = 'sad ';
this.getBvalue=function(){return b;};
}

var a=new A();
alert(a.getBvalue());

你在A里面var声明了b,它只能做为A的私有变量了,所以你必须写一个方法getBvalue()来得到它,用 a.getBvalue()可以 a.b是不行的
  相关解决方案