+ -
当前位置:首页 → 问答吧 → 这是为什么?

这是为什么?

时间:2011-09-03

来源:互联网

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

作者: fdsa43t34dsfaf23   发布时间: 2011-09-03

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

作者: BLUE_LG   发布时间: 2011-09-04

JScript code

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();

作者: hookee   发布时间: 2011-09-04

var test = function () { num = 0 ;};

这样是声明了一个全局变量num, 相当于window.num = 0;

var test = function () { this.num = 0 ;};

这样就是给函数的调用对象增加了一个名为num的属性;


如果你想写在函数外面,可以这样
 
var testit = new test();
testit.num = 0;
...  

作者: danica7773   发布时间: 2011-09-04