使用John Resig的"简单JavaScript继承"如何在方法中调用超级方法PLUS额外代码?

nat*_*e75 1 javascript inheritance resig class extend

我决定尝试JavaScript天才John Resig的"简单JavaScript继承",详见本博客页面:

http://ejohn.org/blog/simple-javascript-inheritance/

我很好奇如何使用调用super方法的代码覆盖方法.换句话说,假设我从Person类开始:

var Person = Class.extend({
    init: function ( name, age ) {
        this.name = name;
        this.age = age;
    }
});
Run Code Online (Sandbox Code Playgroud)

我扩展了Person类来创建一个新的类Worker:

var Worker = Person.extend({
    init: function ( name, age, occupation ) {
        this.name = name;
        this.age = age;
        this.occupation = occupation;
    }
});
Run Code Online (Sandbox Code Playgroud)

在两个版本的init方法中重复了代码.无论我使用哪个类,都会执行以下两行:

this.name = name;
this.age = age;
Run Code Online (Sandbox Code Playgroud)

好像我应该能够调用人员类的初始化从内法英雄类的初始化方法,然后在代码与额外的行抛出的职业属性.

但是,我不能用Resig先生的代码那样做.以下不起作用:

var Worker = Person.extend({
    init: function ( name, age, occupation ) {
        this._super(arguments);
        this.occupation = occupation;
    }
});
Run Code Online (Sandbox Code Playgroud)

一旦从Person调用的extend方法创建了Worker类,就会看到*this._super(arguments)*它用Person的init替换整个Worker的init,给我留下一个未定义的占用属性.

有没有人有任何关于如何解决这个问题的建议,而无需修改Resig先生的代码?我目前正在尝试不同的方式来实现"超级"的概念,但事实上我无法使用现有的代码来解决这个问题.:-)

更新:我意识到我在实现Resig先生的代码时犯了一个小错误,这就是为什么我的行为与我描述的方式相同.@chuckj也正确指出了Worker的 init中的错误.

chu*_*ckj 5

将Worker定义更改为,

var Worker = Person.extend({ 
    init: function (name, age, occupation) { 
        this._super(name, age); 
        this.occupation = occupation; 
    } 
}); 
Run Code Online (Sandbox Code Playgroud)

你没有传递arguments数组,你_super用它期望的参数调用.