Javascript 如何修复此示例,使其在第一个或第二个子类之后工作?

Javascript 如何修复此示例,使其在第一个或第二个子类之后工作?,javascript,Javascript,在本例中,我尝试创建一个类模板,然后使用它创建一个基“类”,依此类推 在我到达NewStudent之前,一切都很顺利。我得到一个类型错误“对象不是函数” var Class = function(options) { var newClass = function(options) { $.extend(this, options); }; if (options) { $.extend(newClass, options); }

在本例中,我尝试创建一个类模板,然后使用它创建一个基“类”,依此类推

在我到达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);
};
致:

它执行speak调用,但名称为空,类型未知

我将jquery用于$.extend方法


我如何才能改进它,使其工作?我试图做一些类似于Mootools类的事情,只是我想创建自己的裸体版本

你把对象和函数混淆了

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();

上面的代码可以在这里执行:

因此对函数调用new将返回一个对象。我将尝试将其自动化一个级别,以避免调用Class.create(如果可能的话)。谢谢你的帮助!您不能期望“new Student()”为您创建一个新类,同时允许您创建一个类型为“Student”的新对象。我不认为你能让它比我展示的简单很多。我做了一个小的改变,使它更易于使用。是的,我回应得太快了。我想了很久,意识到我对这个问题的想法是错误的。现在我更清楚地理解了,也理解了Mootools中的类结构具有Implements/Extends选项的原因。
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();