2014-02-06 17 views
0

我使用John Resig的簡單javascript inheritance code來構建和擴展類。我喜歡他的例子一些類:確定一個函數是否使用Resig的簡單JavaScript繼承擴展另一個函數

var Person = Class.extend({ 
    init: function(isDancing){ 
    this.dancing = isDancing; 
    }, 
    dance: function(){ 
    return this.dancing; 
    } 
}); 

var Ninja = Person.extend({ 
    init: function(){ 
    this._super(false); 
    }, 
    dance: function(){ 
    // Call the inherited version of dance() 
    return this._super(); 
    }, 
    swingSword: function(){ 
    return true; 
    } 
}); 

我想我可以通過一個變量的函數,如果變量是一個類,從Person繼承,還是假的,如果它不是,它將返回true。

「從Person繼承」我的意思是它是通過調用Person的.extend()函數或從Person繼承的類創建的。

如果我有一個類的實例,我可以使用instanceof來確定類是否繼承自Person。有沒有辦法做到這一點沒有創建實例

謝謝!

+0

他的擴展實際上只是複製屬性,不涉及任何繼承。我擔心你的任務是不可能的,除非是靜態分析師或某種昂貴的反射嗅探。 – dandavis

回答

1

您可以簡單地使用instanceof operator與類的原型:

function isPersonSubclass(cls) { 
    return typeof cls == "function" && cls.prototype instanceof Person; 
} 

isPersonSubclass(Ninja) // true 
1

看代碼,它看起來像原型對象設置爲父 「類」 的一個實例:

// Instantiate a base class (but only create the instance, 
// don't run the init constructor) 
var prototype = new this(); 

// [...] 

Class.prototype = prototype; 

所以,你可以這樣做:

Ninja.prototype instanceof Person 

DEMO

相關問題