我用js写了一个类
function AA(name){
    this.name = name;
    this.obj=new Object();
}AA.prototype.onclick = function(){
   var str="Hello:";
    this.obj.onchange = function()
    {
         alert(this.name);//我在这个地方想调用AA中的this.name.报错,说没有定义,我应该怎样才能访问到AA中的this.name呢?谢谢
    }
};

解决方案 »

  1.   


     AA.prototype.onclick = function() {
                var str = this.name;
                alert(str);
            };
      

  2.   

    作用域的问题, 
    this.obj.onchange = function() 
        { 
            alert(this.name);//我在这个地方想调用AA中的this.name.报错,说没有定义,我应该怎样才能访问到AA中的this.name呢?谢谢 
        } 
    alert后面的this指的是this.obj.onchange = function()这个this的
    而不是function AA(name)这个要搞清楚,要搞明白this的作用域。
      

  3.   

    我需要在
     this.obj.onchange 事件中去获取上面的this.name
      

  4.   

    我不是给你写了吗
    var str = this.name;
    this.obj.onchange = function() 
        { 
            alert(str );
        } 
    这样就行了啊
      

  5.   

    AA.prototype.onclick = function() {
    你先在这个function中获取到父母的信息
    下面怎么用都行的
      

  6.   

    5 楼说的没错,确实是作用域的问题,其实 Javascript 本身提供了解决的办法:
    function AA(name){
        this.name = name;
        this.obj=new Object();
    }AA.prototype.onclick = function(){
        var str="Hello:";
        this.obj.onchange = (function()
        {
            alert(this.name);
        }).apply(this);  //调用 apply 方法,设置 onchange 方法内的 this 指向 AA 本身。
    }; var a = new AA('a');
    a.onclick();
    a.obj.onchange();