我如何修复此示例,以便它在第一个或第二个子类之后工作?

时间:2011-12-21 18:26:35

标签: javascript

在这个例子中,我正在尝试创建一个Class模板,然后用它来创建一个基类'class',依此类推。

这一切都有效,直到我到达NewStudent。我得到一个类型错误'对象不是函数'。

var Class = function(options) {
    var newClass = function(options) {
        $.extend(this, options);
    };

    if (options) {
        $.extend(newClass, options);
    }

    newClass.prototype = newClass;
    newClass.prototype.constructor = newClass;
    return newClass;
};

var Person = new Class();
Person.prototype.speak = function() {alert(this.name + ', ' + this.type);}


var Student = new Person({name: 'Student', type: 'Student'});
Student.speak();

var NewStudent = new Student({name: 'NewStudent'});
NewStudent.speak();

如果我改变:

var newClass = function(options) {
    $.extend(this, options);
};

到:

var newClass = function(options) {
    $.extend(this, options);
    return newClass;
};

它执行说话呼叫,但名称为空,且类型未识别。

我正在使用jquery作为$ .extend方法。

如何改善这一点以便它有效?我正在尝试做类似于Mootools他们的类的方式,除了我想创建我自己的准系统版本。

1 个答案:

答案 0 :(得分:2)

您将对象与功能混淆。

Person变量是一个函数,但Student变量是一个普通的对象,所以你不能“新”它。

您必须创建一个单独的函数来创建派生类。我稍微改了一下你的例子,想出了这个:

Class = function(ParentClass, options) {

    if (ParentClass && typeof(ParentClass) != 'function') {
      options = ParentClass;
      ParentClass = undefined;
    }

    var ctr = function(objOptions) {
      $.extend(this,objOptions);
    };

    if (typeof(ParentClass) == 'function') {
      ctr.prototype = new ParentClass();
    }

    $.extend(ctr.prototype,options);

    ctr.Derive = function(options) { return new Class(ctr,options); };

    return ctr;
};

然后你可以做你想做的事情:

var Person = new Class({ speak: function() {alert(this.name + ', ' + this.type);} });
var Student = Person.Derive({type: 'Student'});
var NewStudent = Student.Derive({type:"NewStudent"});

var student = new Student({name: 'student'});
student.speak();

var newStudent = new NewStudent({name: 'newStudent'});
newStudent.speak();

上面的代码可以在这里执行:http://jsbin.com/unetox/6