Javascript child 的构造函数名称

标签 javascript oop inheritance

问题

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

解释

让我们上课Cat扩展了 Model类(class)。和类Kitten扩展了 Cat类。

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

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

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

# 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

最佳答案

这就是我使用 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

关于Javascript child 的构造函数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14484131/

相关文章:

javascript - Extjs4 - ExtJs 3's panel ' findByType' 方法的等效项是什么?

javascript - onmousedown 事件对象行为异常

javascript - aria-expanded 和 aria-haspopup 属性是否适用于 <select/> 元素?

java - 是什么让对象字段自动改变?

function - 将继承的帧作为参数传递给过程

c# - GetHashCode 应该取决于类型吗?

javascript - 继承 toString()

javascript - Angular 与 wavesurfer.js 在 IE10 中不起作用

javascript - 为什么在 JavaScript 中使用 new 和构造函数是错误的

c# - 对待对象就像他们是 parent 一样