以下为个人总结:
为了与面向对象靠拢,javascript也可以用类型,继承等方案模拟面向对象
1.一个函数就是一个类。类名就是函数名,构造函数就是函数本身。代码如下:
function Rectangle(w,h)
{
//初始化对象的属性
this.width = w;
this.heigh = h;
}
以上代码中Rectangle就是类名,Rectangle(w,h)就是构造方法。产生Rectangle的对象就是
var r = new Rectangle(2,3);
2.添加实例对象的方法和属性
1)添加实例对象的方法有两种方法
//第一种方法
function Rectangle_area()
{
return this.width*this.height;
}
Rectangle.prototype.area = Rectangle_area;
//第二种方法
Rectangle.prototype.area = function()
{
return this.width*this.height;
}
//显然,第二种方法更直观点
2)添加实例对象的属性
//如果要添加一个周长的属性
this.perimeter = 2(this.width+this.height);
3)添加类的对象
//创建一个教Compare的类方法(使用起来有点像静态方法)
Rectangle_Compare(a,b)
{
if(a.weigh*a.height > b.wight*b.height)
{
return a;
}
else
{
return b;
}
}
Rectangle.Compare = Rectangle_Compare;
4)添加类的属性
//加入一个教PI的类属性(类似于静态属性)
Rectangle.PI = 3.14159;
5)prototype是类型的圆形,每个类都有原型,是一个object类的引用
6)超类和子类:如果你想模拟面向对象里的继承的关系可以使用子类类型的原型为父类,并且重新指向构造属性(constructor),示例如下
//父类,是一个虚数类
function Complex(real,imaginary)
{
this.x = real;
this.y = imaginary;
}

//子类
function MoreComplex(real,imaginary)
{
this.x = real;
this.y = imaginary;
}
//原型为父类的一个对象
MoreComplex.prototype = new Complex(0,0);
//子类的新方法
MoreComplex.prototype.swap = function()
{
var tmp = this.x;
this.x = this.y;
this.y = temp;
}
//重指向构造属性
MoreComplex.prototype.constructor = MoreComplex;
Javasript的面向对象的模拟似乎就这么点了。有事件再去看看json里有点什么东西。
为了与面向对象靠拢,javascript也可以用类型,继承等方案模拟面向对象
1.一个函数就是一个类。类名就是函数名,构造函数就是函数本身。代码如下:
function Rectangle(w,h)
{
//初始化对象的属性
this.width = w;
this.heigh = h;
}
var r = new Rectangle(2,3);1)添加实例对象的方法有两种方法
//第一种方法
function Rectangle_area()
{
return this.width*this.height;
}
Rectangle.prototype.area = Rectangle_area;
//第二种方法
Rectangle.prototype.area = function()
{
return this.width*this.height;
}
//显然,第二种方法更直观点
//如果要添加一个周长的属性
this.perimeter = 2(this.width+this.height);
//创建一个教Compare的类方法(使用起来有点像静态方法)
Rectangle_Compare(a,b)
{
if(a.weigh*a.height > b.wight*b.height)
{
return a;
}
else
{
return b;
}
}
Rectangle.Compare = Rectangle_Compare;
//加入一个教PI的类属性(类似于静态属性)
Rectangle.PI = 3.14159;6)超类和子类:如果你想模拟面向对象里的继承的关系可以使用子类类型的原型为父类,并且重新指向构造属性(constructor),示例如下
//父类,是一个虚数类
function Complex(real,imaginary)
{
this.x = real;
this.y = imaginary;
}
//子类
function MoreComplex(real,imaginary)
{
this.x = real;
this.y = imaginary;
}
//原型为父类的一个对象
MoreComplex.prototype = new Complex(0,0);
//子类的新方法
MoreComplex.prototype.swap = function()
{
var tmp = this.x;
this.x = this.y;this.y = temp;
}//重指向构造属性
MoreComplex.prototype.constructor = MoreComplex;


浙公网安备 33010602011771号