假設我們有以下物件:
class Foo{
constructor(){
this.count = 0。
}
method1() { <does something> }
method2() { <does something else> }
method3() { <做更多的事情> }
}
現在很明顯,我們可以在每個方法中添加以下一行代碼,計數將被更新:
this.count ;
雖然我知道這只是一行代碼,但可以說這是一行多余的代碼。那么是否有辦法讓我們能夠檢測到一個物件方法是否被呼叫,不管是哪一個,然后更新計數?
uj5u.com熱心網友回復:
你可以在一個單獨的物件上迭代添加方法,并讓它們先做this.count 。
class Foo{
constructor(){
this.count = 0。
}
}
const methods = {
method1() {
console.log('m1')。
},
method2() {
console.log('m2')。
},
method3() {
console.log('m3')。
},
};
for (const [key, value] of Object.entries(方法)) {
Foo.prototype[key] = function(...args){
this.count 。
value(...args)。
}
}
const f = new Foo() 。
f.method1()。
f.method1()。
f.method2()。
console.log(f.count);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/313045.html
標籤:
