function Rectangle(w, h)
{
this.width = w; //私有变量
this.height = h; //私有变量
}
上面相当于一个类,要取得私有变量,必须实例化
var rec = new Rectangle(10,20);
rec.width
{
this.width = w; //私有变量
this.height = h; //私有变量
}
上面相当于一个类,要取得私有变量,必须实例化
var rec = new Rectangle(10,20);
rec.width
{
this.width = w;
this.height = h;
}
width 和height 应该是类的属性
function MyClass(w,h)
{
var c=100;//私有变量
this.width = w; //public 属性
this.height = h;
this.getC = function() { //private 属性
return c;
}
}
MyClass.var1="cc";//静态变量</script>
var1可以直接引用MyClass.var1
this.getC=function()....是public属性吧
一般的函数定义和对象的构造函数其实并无区别。
一般的函数定义:如:
function Rectanglen(w, h)
{
return w+h;
}
没有体现出对象的构造函数的特性是因为它没有定义自身类的属性。
其实也可以对以上的函数进行对象化,即new。然后在添加属性。javascript的解释器不区分:
function Rec(w, h)
{
return w+h;
}
和
function RecN(w, h)
{
this.width = w;
this.height = h;
}
是一致的。var Rec1=new(Rec(5,6));
Rec1.width=10;
Rec1.height=8;
和
var Rec2=new(RecN(10,8);
的效果是一致的。以上是我的理解。请大家指正。
{
this.width = w;
this.height = h;
} 也是全局对象的一个方法,只不过这个方法不返回值或者说返回undifined。