function Rectangle(w,h)
{
this.width=w;
this.height=h;
}
当一个函数被定义的时候,JavaScript会创建一个特殊的对象(其类型是function),
对象的名称就是函数的名称,接着创建一个对象为这个函数对象的prototype属性赋值。
以上面的Rectangle 函数为例:
JavaScript创建一个函数对象Rectangle,并且
Rectangle.prototype=new Object();
Rectangle.prototype.constructor=Rectangle
var r=new Rectangle(5,6);
new 会创建一个新的空对象,然后把Rectangle函数赋值给这个对象的constructor属性,
接着调用这个构造函数,最后设置这个对象的原型。一个对象的原型就是它的constructor
的prototype属性的值。
对象创建后,其原型对象确定,如果重新设置其构造函数的prototype,其不受影响。
完整的代码如下:
function Rectangle(w,h)
{
this.width=w;
this.height=h;
}
var r=new Rectangle(10,15);
Rectangle.prototype.area=function(){return this.width * this.height;};
alert(r.area());//150
Rectangle.prototype=new Object();
Rectangle.prototype.area=function(){return this.width+''+this.height;};
alert(r.area());//150
var rr=new Rectangle(10,15);
alert(rr.area());//1015
理解了这些,再去理解模拟类,类属性、类方法、实例属性、实例方法、类继承就容易了