如何在Javascript构造函数的私有方法中访问其属性和公有方法

function Class1(){
    this.i = 1;
    this.aa = function(){
        this.i ++;
    }
    this.bb = function(){
        this.aa();
    }
    this.cc = function(){
        this.bb();
    }
}
var o = new Class1();
o.cc();
document.write(o.i);//return 2

从例子中可以看到构造函数的公有方法访问其属性和其他公有方法是可以的,那么在私有方法中访问公有方法和属性呢?

function Class1(){
    this.i = 1;
    this.aa = function(){
        this.i ++;
    }
    var bb = function(){
        this.aa();
    }
    this.cc = function(){
        bb();
    }
}
var o = new Class1();
o.cc();
document.write(o.i);

脚本出错!提示"对象不支持些属性或方法",错误在"this.aa();"一句,估计是bb被认为是一个新的构造函数,那"this.aa();"中的this已经不再是Class1,因而才提示没有aa方法,那在构造函数的私有方法中如何访问其属性和公有方法呢?下边是无忧脚本winter版主的解答:

function Class1(){
    var me=this;
    this.i = 1;
    this.aa = function(){
        this.i ++;
    }
    var bb = function(){
         me.aa();
    }
    this.cc = function(){
        bb();
    }
}
var o = new Class1();
o.cc();
document.write(o.i);


评论: 0 | 引用: 0 | 查看次数: 5472
发表评论
登录后再发表评论!