【发布时间】:2018-02-08 23:50:58
【问题描述】:
如何用如下方法实现一个类?
class ExistingClass {
function func1() {} // might throw error
function func2() {} // might throw error
get try() {
// Some magic here
return this; // we need to return this to chain the calls, right?
}
}
可以这样称呼
obj.func1() //might throw an error
obj.try.func1() // execute func1 in a try/catch
基本上我想要类似 mochajs 的东西:expect(..).to.not.equal()
更新:
接受的答案应该有效,以下是它的更新版本,支持async 函数
get try() {
return new Proxy(this, {
// Intercept method getter
get: function(target, name) {
if (typeof target[name] === 'function') {
if (target[name][Symbol.toStringTag] === 'AsyncFunction') {
return async function() {
try {
await target[name].apply(target, arguments);
}
catch (e) {}
}
} else {
return function() {
try {
return target[name].apply(target, arguments)
}
catch (e) {}
}
}
}
return target[name];
}
});
}
【问题讨论】:
-
你需要能够调用像
obj.try.func1()这样的函数吗?你能用这样的东西吗:obj.try("func1")? -
get try {... 真的吗?这行得通吗? -
我的两分钱:如果我看到代码或 cmets 沿线“吞下错误”,我会以另一种方式运行。只是说。
-
你应该纠正错误,而不是吞下它们。
-
我看到 mochajs 他们有类似的东西。
expect(val).not.equal()。我会做这样的事情。它使代码更易于阅读。当然,我们不应该接受错误,有一种情况是我们只想“尝试”而error并没有那么重要。无论如何,我只是想知道是否有可能做这样的事情。不过,我从不说这是一个好代码。
标签: javascript method-chaining