【问题标题】:Using John Resig's "simple JavaScript inheritance" how can I call a super method PLUS extra code from within a method?使用 John Resig 的“简单 JavaScript 继承”如何从方法中调用超级方法以及额外代码?
【发布时间】:2012-02-27 00:56:33
【问题描述】:

我决定尝试一下 JavaScript 天才 John Resig 的“简单 JavaScript 继承”,详见此博客页面:

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

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

var Person = Class.extend({
    init: function ( name, age ) {
        this.name = name;
        this.age = age;
    }
});

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

var Worker = Person.extend({
    init: function ( name, age, occupation ) {
        this.name = name;
        this.age = age;
        this.occupation = occupation;
    }
});

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

this.name = name;
this.age = age;

看来我应该能够从 Hero 类的 init中调用 Person 类的 init 方法> 方法,然后用 occupation 属性抛出额外的代码行。

不过,我不能用 Resig 先生的代码做到这一点。以下不起作用:

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

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

有没有人对如何在不修改 Resig 先生的代码的情况下解决这个问题有任何建议?我目前正在尝试不同的方法来实现“超级”的概念,但我无法让它与现有代码一起工作的事实一直困扰着我。 :-)

更新:我意识到我在实现 Resig 先生的代码时犯了一个小错误,这就是我描述的方式的原因。 @chuckj 也正确指出了 Worker's init 中的错误。

【问题讨论】:

    标签: javascript class inheritance extend resig


    【解决方案1】:

    将 Worker 定义更改为,

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

    您没有传递arguments 数组,而是使用它所期望的参数调用_super

    【讨论】:

      【解决方案2】:

      看来您的目标是将arguments 代理到this._super。在这种情况下,你可以apply()他们:

      var Worker = Person.extend({
          init: function ( name, age, occupation ) {
              this._super.apply(this, arguments);
              this.occupation = occupation;
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2012-06-19
        • 2017-06-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-14
        相关资源
        最近更新 更多