看见一些代码,如这样定义
ns.myclass = function(theValue) {
var counter = 0;
var value = theValue;
this.value = value;
this.counter = counter;
}为什么要定义var ,再将var赋给this.var呢? 这样有什么好处?1,4; 2,3这两组,指代的莫非是不同的变量?和如下定义有什么区别?
ns.myclass = function(theValue) {
var counter = 0;
var value = theValue;
}
ns.myclass = function(theValue) {
var counter = 0;
var value = theValue;
this.value = value;
this.counter = counter;
}为什么要定义var ,再将var赋给this.var呢? 这样有什么好处?1,4; 2,3这两组,指代的莫非是不同的变量?和如下定义有什么区别?
ns.myclass = function(theValue) {
var counter = 0;
var value = theValue;
}
<script type="text/javascript">
var a = function(){
var privateTxt = 'private';
this.publicTxt = 'public';
this.getPrivate = function(){alert('通过方法访问到私有成员:'+privateTxt);};
this.setPrivate = function(str){privateTxt = str;};
}var A = new a();
alert('访问属性成员:'+A.publicTxt);//访问属性成员A.publicTxt = 'public A';//直接设置属性成员值
alert('设置后的属性成员值:'+A.publicTxt)alert('访问私有成员:'+A.privateTxt);//试图访问私有成员A.getPrivate();//只能通过方法进行访问私有成员A.setPrivate('private A');//只能通过方法进行设置私有成员
A.getPrivate();
</script>