gpt4 book ai didi

javascript - 如何退出函数级联/链?

转载 作者:行者123 更新时间:2023-11-29 11:01:39 25 4
gpt4 key购买 nike

如果您使用返回 this 的函数创建一个对象,您可以创建一个先前调用的函数链,并创建一个级联的函数调用:

var i = {
foo: function () {
// Something here...
return this;
},

bar: function () {
// Something here...
return this;
}
};

i.foo().bar().foo()

但是,如果在 bar 中发生错误并且我不想在这种情况下调用 foo 怎么办?如何断开级联?

如果可能的话,我想避免使用 try/catch 语句。

最佳答案

好吧,一件直截了当的事情是,如果你想在没有 try/catch 的情况下处理这种情况,你必须在你的函数中加入 if 条件,显然你必须返回一些东西,所以您可以在该上下文而不是异常上执行更多功能。因此,尝试在一个对象中创建所有功能,并仅在有人扩展时才允许执行您的功能逻辑。失败时返回基础,否则返回当前对象。这样您就可以避免每次都创建对象。

例子:让我们考虑一下您有 BaseService,其中定义了所有功能,并在其上放置了一个层以进一步扩展,因此您可以采用这种模式:

foo: function() {
if(<function foo does not belongs to this>) {
.......
.......
if(<on logical failure>) {
return this.__proto__;
}
.......
.......
}
return this;
}

这是一个工作片段:

function BaseService() {
var dataBucket = [13, 50, 45, 57, 95];

this.foo = function() {
if (Object.values(this).indexOf(arguments.callee) === -1) {
console.log('processing foo');
}
return this;
}
this.bar = function() {
if (Object.values(this).indexOf(arguments.callee) === -1) {
console.log('processing bar');
}
return this;
}
this.processValIfExists = function(val) {
if (Object.values(this).indexOf(arguments.callee) === -1) {
console.log('processing processValIfExists');
if (dataBucket.indexOf(val) > -1) {
//process the value further
} else {
return this.__proto__;
}
}
return this;
}
};

//define the extended service, you can add further
//functionalities here. eg: createing the dataBucket here from args
function WrapperService() {};

WrapperService.prototype = new BaseService(); // just extend from any service and use

var svc = new WrapperService();

console.log('----------Executes All-----------');
svc.foo().bar().processValIfExists(95).foo().bar();


console.log('----------Executes upto processValIfExists-----------');
svc.foo().bar().processValIfExists(100).foo().bar();

请注意,这只是我想到的一种不同的方法,为了检查当前的调用方法,我尝试使代码通用,而不是检查它的 WrapperService 实例是否在 BaseService 函数以避免代码耦合,也可以从任何其他服务扩展。

关于javascript - 如何退出函数级联/链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45988530/

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