简体   繁体   English

Javascript儿童的构造函数名称

[英]Javascript children' constructor name

Question

How one could retrieve the children' (of any inheritance depth level) constructor name? 如何检索子级(具有任何继承深度级别)的构造函数名称?

Explanation 说明

Let us have class Cat that extends the Model class. 让我们拥有扩展Model类的Cat类。 And the class Kitten that extends the Cat class. 还有扩展Cat类的Kitten类。

What I want is printed to the console (for example) string "Kitten" when one creates the Kitten class instance and the string "Cat" when one creates the Cat class instance. 我想打印到控制台(例如)字符串"Kitten"当一个创建Kitten类的实例和字符串"Cat" ,当一个创建Cat类的实例。

The trick is that the code that outputs the constructor name should be located at the base ( Model for the example shown) class. 诀窍在于,输出构造函数名称的代码应位于基类(所示示例为Model )。

Note: I'm good at Ruby, compared (in the scope of myself) to Javascript. 注意:与Javascript相比(在我自己的范围内),我擅长Ruby。 So the "pseudo-code" shall be the Ruby-ish one =) 因此, “伪代码”应为Ruby式的=)

# 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

This is how I would do it using Coffee-Script. 这就是我使用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

This is the compiled JavaScript: 这是编译的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();

You can try it yourself here 你可以在这里自己尝试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM