Javascript children的构造函数名称

时间:2013-01-23 16:11:51

标签: javascript oop inheritance

问题

如何检索子项(任何继承深度级别)构造函数名称?

说明

让我们拥有扩展Cat类的类Model。以及Kitten类扩展的类Cat

当一个人创建"Kitten"类实例时,我想要的是打印到控制台(例如)字符串Kitten,当创建"Cat"类时,我会打印字符串Cat实例

诀窍是输出构造函数名称的代码应该位于基类(显示示例的Model)类中。

注意:我擅长Ruby,比较(在我自己的范围内)与Javascript。所以“伪代码”应该是Ruby-ish one =)

# pseudo-Ruby-code
class Model
  def initialize
    console.log(self.constructor.toString())
  end
end

class Cat << Model
  # something goes here
end

class Kitten << Cat
  # and here too
end

# shows "Model"
Model.new

# shows "Kitten"
Kitten.new

# shows "Cat"
Cat.new

1 个答案:

答案 0 :(得分:1)

这就是我使用Coffee-Script的方法。

class Model

    constructor: (animal = "Model") ->

        console.log animal;



class Cat extends Model

    constructor: (animal = "Cat") ->

        super animal


class Kitten extends Cat

    constructor: (animal = "Kitten") ->

        super animal

new Kitten()

// => Kitten

这是已编译的JavaScript:

var Cat, Kitten, Model,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

Model = (function() {

  function Model(animal) {
    if (animal == null) {
      animal = "Model";
    }
    console.log(animal);
  }

  return Model;

})();

Cat = (function(_super) {

  __extends(Cat, _super);

  function Cat(animal) {
    if (animal == null) {
      animal = "Cat";
    }
    Cat.__super__.constructor.call(this, animal);
  }

  return Cat;

})(Model);

Kitten = (function(_super) {

  __extends(Kitten, _super);

  function Kitten(animal) {
    if (animal == null) {
      animal = "Kitten";
    }
    Kitten.__super__.constructor.call(this, animal);
  }

  return Kitten;

})(Cat);

new Kitten();

您可以自己尝试here