prototype(原型) 是 JavaScript 中类的继承手段;

一个类也不过是一组属性和方法的集合, 所谓继承就是继承属性或方法;

属性是个值, 方法是个函数, JavaScript 喜欢把它们都叫成属性, 我们喜欢把它们叫做成员;

JavaScript 默认让每个函数都拥有一个 prototype 对象, 它可以指向一个对象或函数(函数也是对象, 一回事);

绕来绕去, 最终是四通八达...

类成员与对象成员
function Rect(w, h) {
  Rect.name = "My Rect"; //静态成员属于类, 不会被对象继承; 须冠类名调用
  this.width = w;        //this 是指实例化以后的对象或调用该函数的对象
  this.height = h;
  xyz = 123;            //这只能当个内部变量来使用
}

var r = new Rect();

//判断指定的成员名是否属于对象
alert("width" in r);  //true
alert("height" in r); //true
alert("name" in r);   //false

//遍历对象成员
for (x in r) {
  alert(x);           //width / height
}

//遍历类成员
for (x in Rect) {
  alert(x);           //name
}


继承
function Point(x, y) {
  this.x = x;
  this.y = y;
};

function Rect(w, h) {
  Rect.name = "My Rect";
  this.width = w;
  this.height = h;
}
Rect.prototype = new Point(); //让 Rect 再从 Point 类继承

var r = new Rect();

//继承以后就可以这样使用
r.x = 1;
r.y = 2;
r.width = 3;
r.heigth = 4;

//遍历对象成员
for (x in r) {
  alert(x); //y / x / width / height
}

//遍历类成员
for (x in Rect) {
  alert(x); //name
}

//建立方法 constructor 属于 prototype, 既然 Rect 是继承与 Point, 那么:
alert(r.constructor); /* 将显示:
function Point(x, y) {
  this.x = x;
  this.y = y;
};
*/


hasOwnProperty、propertyIsEnumerable、isPrototypeOf
function Point(x, y) {
  this.x = x;
  this.y = y;
};

function Rect(w, h) {
  Rect.name = "My Rect";
  this.width = w;
  this.height = h;
}
Rect.prototype = new Point();

var r = new Rect();

/* 可用 hasOwnProperty 方法判断指定成员是否是对象的固有成员(而非继承来的) */
alert(r.hasOwnProperty('x'));      //false
alert(r.hasOwnProperty('y'));      //false
alert(r.hasOwnProperty('width'));  //true
alert(r.hasOwnProperty('height')); //true

/* 但不能用 hasOwnProperty 判断成员是否是继承来的, 譬如 */
alert(r.hasOwnProperty('ABCDEFG')); //false

/* propertyIsEnumerable */
alert(r.propertyIsEnumerable('x'));      //false
alert(r.propertyIsEnumerable('y'));      //false
alert(r.propertyIsEnumerable('width'));  //true
alert(r.propertyIsEnumerable('height')); //true

/* isPrototypeOf: 是不是参数(参数是个对象)的原型对象 */
alert(Point.prototype.isPrototypeOf(r));    //true
alert(Rect.prototype.isPrototypeOf(r));     //true
alert(r.isPrototypeOf(r));                  //true

var obj = {};
alert(Object.prototype.isPrototypeOf(obj)); //true
var str = new String();
alert(String.prototype.isPrototypeOf(str)); //true
alert(Object.prototype.isPrototypeOf(str)); //true


posted on 2009-03-04 11:45  万一  阅读(1670)  评论(0编辑  收藏  举报