【问题标题】:Print subclass name instead of 'Class' when using John Resig's JavaScript Class inheritance implementation [closed]使用 John Resig 的 JavaScript 类继承实现时打印子类名称而不是“类”[关闭]
【发布时间】:2023-03-06 18:46:02
【问题描述】:

我正在 John Resig 的 class inheritance implementation (javascript) 之上构建一个系统

除了出于检查/调试目的(也许是为了稍后进行类型检查,我想处理实例化类的实际名称之外)一切都很好。

例如:按照 John 的示例,返回 Ninja 而不是 Class

我知道这个名字来自this.__proto__.constructor.name,但这个道具是只读的。我想它必须是子类本身初始化的一部分。

有人吗?

【问题讨论】:

    标签: javascript inheritance


    【解决方案1】:

    如果您仔细查看代码,您会看到如下几行:

    Foo.prototype = new ParentClass;//makes subclass
    Foo.prototype.constructor = Foo;
    

    如果省略第二行,构造函数名称将是父类的名称。 name 属性很可能是只读的,但prototype 不是,原型的constructor 属性也不是。这就是您可以设置 "class"/constructor 的名称的方法。

    还要注意__proto__ 不是获取对象原型的方法。最好使用这个 sn-p:

    var protoOf = Object && Object.getPrototypeOf ? Object.getPrototypeOf(obj) : obj.prototype;
    //obviously followed by:
    console.log(protoOf.constructor.name);
    //or:
    protoOf.addProtoMethod = function(){};//it's an object, thus protoOf references it
    //or if all you're after is the constructor name of an instance:
    console.log(someInstance.constructor.name);//will check prototype automatically
    

    就这么简单,真的。

    【讨论】:

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