首页 > 语言 > JavaScript > 正文

Prototype Class对象学习

2024-05-06 14:14:46
字体:
来源:转载
供稿:网友
代码如下:
/* Based on Alex Arnell's inheritance implementation. */

var Class = (function() {
//临时存储parent的prototype
function subclass() {};

//创建类的方法
function create() {
var parent = null, properties = $A(arguments);
    //检查新建一个类时,是否指定了一个父对象
    //如果指定了父类,赋值给parent
if (Object.isFunction(properties[0]))
parent = properties.shift();

//真正用作返回的类,在创建实例时,将调用initialize方法进行初始化
function klass() {
this.initialize.apply(this, arguments);
}

//给klass添加addMethods方法,在调用create方法之后
    //仍可以调用addMethods方法进行类级别的方法扩充
Object.extend(klass, Class.Methods);
    //给返回的类添加两个属性,superclass:父类,subclasses:子类的集合
klass.superclass = parent;
klass.subclasses = [];

//如果创建类时指定了父对象,则把klass的原型指向父对象的实例,实现原型链继承
if (parent) {
subclass.prototype = parent.prototype;
klass.prototype = new subclass;
     //为父类添加子类,维护父类的子类集合
parent.subclasses.push(klass);
}

//向新类添加方法
for (var i = 0; i < properties.length; i++)
klass.addMethods(properties[i]);

//如果没有指定初始化方法,则默认把一个空方法赋给初始化方法
if (!klass.prototype.initialize)
klass.prototype.initialize = Prototype.emptyFunction;

    /*
     * 修正新类的构造函数,使得构造函数指向自己,这里特意说一下(如果注释掉下面这行):
     * var Person=Class.create();
     * var p1=new Person();
     * alert(p1.constructor==Person) //true
     * var Man=Class.create(Person)
     * var m1=new Man();
     * alert(m1.constrcutor==Man) //false
     * alert(m1.constrcutor==Person) //true
     * alert(m1.construcctor==p1.constrcutor) //true
     *
     * 看出问题来了吧?Man的构造函数竟然指向了Person的构造函数
     * 问题的根源在klass.prototype = new subclass;这句话
     * 具体原因我就不解释了,要详细理解的请查看《JavaScript语言精髓与编程实践》155~160页
    */
klass.prototype.constructor = klass;
return klass;
}

//把创建类时的方法添加到新类,或者在创建完类之后在添加类级别的方法
function addMethods(source) {
    //取得新类的父类
var ancestor = this.superclass && this.superclass.prototype;
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选