window.onload = function(){
var init = box.getArea();
alert(init);
}
由于没有对init中的width,height进行初始化,所以会报错,这样改一下:
var box = {
width:0,
height:0,
getArea:function(){
return width*height;
},
init:function(w,h){
width = w;
height = h;
}
}
window.onload = function(){
width = 0;
height = 0;
//or box.init(0,0);
var init = box.getArea();
alert(init);
}
发现可以了,由于init和 getArea所用的width和height并不是归单体所有的变量,而是一个全局变量,所以我们可以在单体外面进行随意调用而不受影响
如果我们这样写一下就更明白了:
var box = {
width:0,
height:0,
getArea:function(){
return width*height;//js中对象成的访问必须是显示的,即this是不能省略的
},
init:function(w,h){
width = w;
height = h;
}
}//这里的width,height其实并不是单体的对象
window.onload = function(){
width = 0;
height = 0;
var width = box.getArea();
alert(width);
}
这样写又会报错了,可见我们以上的方式对于全局变量并没有建立起一个命名空间,全局变量为我们带来了危险。所以最上面的写法是对的,我们来验证一下:
var box = {
width:2,
height:2,
getArea:function(){
return this.width*this.height;//js中对象成的访问必须是显示的,即this是不能省略的
},
init:function(w,h){
this.width = w;
this.height = h;
}
}
window.onload = function(){
width = 0;
height = 0;
var width = box.getArea();
alert(width);
}
可见在window.onload中的width 和height已经没有干扰了,因为单体为单体中的width和height建立了一个命名空间。
成员的属性:
讨论完命名空间,我们来对单体变量和方法的属性做一下设定。学过其他语言的人(java,c++,c#...)都应该很了解其中类成员的public和private,
虽然在javascript中没有这么严格的面向对象(oop),但是我们可以借助闭包来进行一个模仿,毕竟有的变量设为public是很不好的。
var circle = (function(){
//pravite member!
var r = 5;
var pi = 3.1416;//后面用分号
return{//public member
getArea:function(){
return r*r*pi;//访问私有成员不要加this
},//后面用逗号
//如果想改变r和pi的值,只能通过设置一个公有的函数来实现
init:function(setR){
r = setR;
}
}
})()
window.onload = function(){
circle.r = 0;//无法访问私有成员,相当于又为circle创建了一个共有成员r
alert(circle.getArea());
circle.init(0);//通过公有的工具函数便可以访问了。
alert(circle.getArea());
};
私有变量、方法是只读的,公有变量、方法是可读可写的










