[英]Javascript: Get subclass type in superclass
I am using this to create a few classes and to set up some inheritance structure. 我使用它来创建一些类并设置一些继承结构。
var ControlType = Class.extend({
init: function(){ },
html: function(type){
//Get template based on name of subclass
}
});
var YesNo = ControlType.extend({
init: function(){ },
html: function() {
this._super('YesNo')
}
});
Now I was wonder if it's possible to get the type of the subclass in ControlType.html
without passing it explicitly? 现在我想知道是否可以在
ControlType.html
获取子类的类型而不显式传递它?
I tried this.constructor
without the extend functionality as someone suggested but this returns the type of the parent class. 我尝试了
this.constructor
而没有像某人建议的扩展功能,但这会返回父类的类型。 So in the following example the console logs Person() but I need Jimi(). 所以在下面的例子中,控制台记录了Person()但我需要Jimi()。
function Person(){
this.say = function(){
console.log(this.constructor);
}
}
function Jimi(){
this.name = 'Jimi';
}
Jimi.prototype = new Person();
var j = new Jimi();
j.say();
Hard to pick since there are actually a few different ways you could do this. 很难选择,因为实际上有几种不同的方法可以做到这一点。 I guess maybe the easiest would be something like this:
我想最简单的可能是这样的:
function Person(){
this.name = 'Person'; //<<< ADDED THIS
this.say = function(){
console.log(this.name); //<<< ADDED THIS
}
}
function Jimi(){
this.name = 'Jimi';
}
Jimi.prototype = new Person();
var j = new Jimi();
j.say();
This will then output 然后输出
Jimi
Hopefully it helps! 希望它有所帮助!
It looks like you are using some kind of inheritance library. 看起来你正在使用某种继承库。 I'm not sure what
extend
does, but in plain JavaScript, you can use this.constructor
to refer to the constructor function of an object. 我不确定
extend
作用,但在纯JavaScript中,您可以使用this.constructor
来引用对象的构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.