gpt4 book ai didi

javascript - 我可以在 JavaScript 中定义 "fallback"方法吗?

转载 作者:搜寻专家 更新时间:2023-11-01 04:19:25 27 4
gpt4 key购买 nike

是否可以(以高效的方式)在 JavaScript 中定义“回退”方法?

例如

function MyObject () {
/* what do i have to add here to have my defaultMethod? */
}

var obj = new MyObject ();
obj.doesntExistInMyObject (); // I want defaultMethod to be called
obj.doesntExistEither (); // I want defaultMethod to be called, too

即:我希望在编写 obj.calledMethod ();obj.calledMethod == undefined 时调用 defaultMethod,但是我不想在调用代码中检查 undefined

最佳答案

JavaScript 目前没有该功能。不过,它可能会在下一个版本中通过 proxies .所以在那之前,要做到这一点,你必须做一些相当丑陋的事情,比如:

MyObject.prototype.ex = function(fname) {
var f = this[fname],
args = Array.prototype.slice.call(arguments, 1);
if (typeof f === "function") {
return f.apply(this, args);
}
return this.defaultMethod.apply(this, args);
};

...并像这样使用它:

var obj = new MyObject();
obj.ex("doesntExistInMyObject", "arg", "arg");

(ex 表示“执行”,因为 call 很容易与 Function#call 混淆。)

关于javascript - 我可以在 JavaScript 中定义 "fallback"方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10775580/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com