var test = function () { num = 0 ;}; 
test.prototype.show = function () { alert(this.num) ; } 
test.prototype.add = function () { this.num += 1 ; alert(this.num);} 
var testit = new test() ; 
testit.add();  //NaN 
testit.show();  //NaN 
为什么 testit.add();  和 testit.show(); 显示结果不是 1 呢? 而是 NaN? 我哪里错了? 为什么 
var test = function () { this.num = 0 ;};  就可以呢? 
//asker:www.yuanshi88.com

解决方案 »

  1.   

    你说如果num是在函数外定义的怎么办?
    this.num使得num和函数变量test绑定
      

  2.   


    var test = function () {this.num = 0 ;};  
    test.prototype.show = function () { alert(this.num) ; }  
    test.prototype.add = function () { this.num += 1 ; alert(this.num);}  
    var testit = new test();  
    testit.add(); 
    testit.show();
      

  3.   

    var test = function () { num = 0 ;};这样是声明了一个全局变量num, 相当于window.num = 0;var test = function () { this.num = 0 ;};这样就是给函数的调用对象增加了一个名为num的属性;
    如果你想写在函数外面,可以这样
     
    var testit = new test();
    testit.num = 0;
    ...