【问题标题】:Determine if a function extends another using Resig's simple javascript inheritance使用 Resig 的简单 javascript 继承确定一个函数是否扩展另一个函数
【发布时间】:2014-02-06 22:45:48
【问题描述】:

我正在使用 John Resig 的简单 javascript inheritance code 来构建和扩展类。我有一些像他的例子一样的课程:

var Person = Class.extend({
  init: function(isDancing){
    this.dancing = isDancing;
  },
  dance: function(){
    return this.dancing;
  }
});

var Ninja = Person.extend({
  init: function(){
    this._super( false );
  },
  dance: function(){
    // Call the inherited version of dance()
    return this._super();
  },
  swingSword: function(){
    return true;
  }
});

我想要一个可以传递变量的函数,如果变量是继承自 Person 的类,它将返回 true,否则返回 false。

“继承自 Person”是指它是通过调用 Person 或继承自 Person 的类的 .extend() 函数创建的。

如果我有一个类的实例,我可以使用 instanceof 来确定该类是否继承自 Person。有什么方法可以做到这一点不创建实例

谢谢!

【问题讨论】:

  • 他的扩展实际上只是复制属性,不涉及继承。我担心你的任务是不可能的,除非有静态分析师或某种昂贵的反射嗅探。

标签: javascript inheritance


【解决方案1】:

您可以简单地将instanceof operator 与类的原型一起使用:

function isPersonSubclass(cls) {
    return typeof cls == "function" && cls.prototype instanceof Person;
}

isPersonSubclass(Ninja) // true

【讨论】:

    【解决方案2】:

    看代码,原型对象被设置为父“类”的一个实例:

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    var prototype = new this();
    
    // [...]
    
    Class.prototype = prototype;
    

    所以你可以这样做:

    Ninja.prototype instanceof Person
    

    DEMO

    【讨论】:

      猜你喜欢
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 2015-07-07
      • 2015-03-16
      • 1970-01-01
      相关资源
      最近更新 更多