Javascript:获取超类中的子类类型

时间:2010-07-17 16:53:42

标签: javascript

我正在使用this创建一些类并设置一些继承结构。

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')
    }
});

现在我想知道是否可以在ControlType.html中获取子类的类型而不明确地传递它?

更新

我尝试了this.constructor没有像某人建议的扩展功能,但这会返回父类的类型。所以在下面的例子中,控制台记录了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();

2 个答案:

答案 0 :(得分:3)

很难选择,因为实际上有几种不同的方法可以做到这一点。我想最简单的可能就是这样:

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();

然后输出

Jimi

希望它有所帮助!

答案 1 :(得分:0)

看起来你正在使用某种继承库。我不确定extend的作用,但在纯JavaScript中,您可以使用this.constructor来引用对象的构造函数。

相关问题