2 回答

TA贡献1890条经验 获得超9个赞
您可能根本不需要诺言async/await,我想您可以创建一个Proxy对象来拦截后续调用。
这个想法是,当.delay(duration)被调用时,它将返回一个代理对象而不是类实例。此代理对象将拦截方法调用,为设置超时duration,然后使用原始类实例调用该方法。
class J {
constructor(selector) {
this.$element = document.querySelector(selector)
}
delay(duration) {
const proxy = new Proxy(this, {
get: (target, prop) => {
const f = target[prop]
return (...args) => {
setTimeout(() => {
return f.apply(target, [...args])
}, duration)
// return the class instance again, so subsequent call & delay still works
return this
}
}
})
return proxy
}
text(content) {
this.$element.textContent = content
return this
}
}
const $ = selector => new J(selector)
$('#test').text('hello').delay(1000).text('world')
<div id="test"></div>
添加回答
举报