我正在寫一些擴展父類的JS,我想知道是否有方法可以告訴子類是否使用父方法而未調用它。理想情況下,我希望在父項的構造函數中運行檢查,以查看是否有任何子方法正在方法定義中使用父項的方法。javascript - 檢查子方法中是否使用父方法
我已經完成了一些研究,並且遇到了類似Object.getOwnPropertyNames()
的東西,但我不確定我是否朝着正確的方向前進。
例如:
class Path {
constructor (name) {
// how can I check if addRelationship have been used? If possible.
this.relationships = {};
this.currentRelationship = '';
this.path = path;
}
addRelationship (relationship) {
// do something
this.currentRelationship = relationship.path;
return this;
}
makePath() {
let path = [this.path];
if(this.currentRelationship) {
path.push(this.currentRelationship)
}
return path.join("/");
}
}
class OnePath extends Path {
// ...
someMethodFromThatRelationship() { }
}
class TwoPath extends Path {
// ...
}
var onePath = new OnePath('one');
var twoPath = new TwoPath('two-path');
class SomeOtherPath extends Path {
one() {
return this.addRelationship(onePath);
}
two() {
return this.addRelationship(twoPath);
}
}
上面的例子中的想法是,如果addRelationship
在任何引用的方法我可以檢查,如果是這樣,one()
和two()
實際上是在調用之前註冊this.relationships.one
和this.relationships.two
。我希望我有道理。我很想知道這是否可能。
更新
上面的代碼的最終結果將是做到以下幾點能力:
let someOtherPath = new SomeOtherPath('some-other-path');
// now I can call
someOtherPath.relationships.one.someMethodFromThatRelationship();
// and can also call the save method from the extended class
someOtherPath.one().makePath();
// some-other-path/one
// I can also just call
someOtherPath.makePath();
// some-other-path
你想創建一個接口嗎? –
@凱斯霍利迪最高興的是,是的。或者至少是某種形式的界面。 –
你的[實際問題](http://meta.stackexchange.com/q/66377)是什麼?你只需要獲取子類的方法名稱,或者實際上只需要那些調用'addRelationship'的方法? – Bergi