[英]Javascript: Get subclass type in superclass
我使用它來創建一些類並設置一些繼承結構。
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();
很難選擇,因為實際上有幾種不同的方法可以做到這一點。 我想最簡單的可能是這樣的:
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
希望它有所幫助!
看起來你正在使用某種繼承庫。 我不確定extend
作用,但在純JavaScript中,您可以使用this.constructor
來引用對象的構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.