gpt4 book ai didi

javascript - 在运行功能之前检查条件的最佳方法是什么

转载 作者:行者123 更新时间:2023-11-30 14:37:57 25 4
gpt4 key购买 nike

我需要在调用函数之前检查一些条件,这些函数是从不同的 js 文件(如 index.js 或 app.js)调用的。

在调用其他人之前检查条件的最佳方法是什么?考虑一下您正在做类似身份验证的事情,如果用户已通过身份验证,则调用该函数。我需要检查 30 个函数的条件。

我不需要对函数进行更改,而是需要编写一个函数/属性/任何需要影响其他函数的函数/属性。

file1.js:
function1
function2
function3
...
function30

file2.js:
file1.function1();

file3.js:
file1.function15();

最佳答案

举个例子来说明我在评论中的建议,这是一种用身份验证检查包装每个函数的简单方法,不会给您的调用增加太多困惑。

// Some mock up of you existing code
var authenticated = true;

function thing1() { alert(1); }
function thing2() { alert(2); }
function thing3() { alert(3); }

// New code
function checkAuthAndRun(func) {
if (authenticated) {
func();
} else {
console.log("User is not allowed to do this");
}
}

// Calling your functions
checkAuthAndRun(thing1);
checkAuthAndRun(thing2);
checkAuthAndRun(thing3);

带参数的例子

// Some mock up of you existing code
var authenticated = true;

function thing1() {alert(1); }
function thing2(a) { alert(a); }
function thing3(a, b) { alert(a + b); }

// New code
function checkAuthAndRun(func) {
if (authenticated) {
// This line will need to have as many arguments[x] parameters as the function
// with the most parameters that you will call through this method
func(arguments[1], arguments[2]);
} else {
console.log("User is not allowed to do this");
}
}

// Calling your functions
checkAuthAndRun(thing1);
checkAuthAndRun(thing2, "Parameter 1");
checkAuthAndRun(thing3, "Parameter 1", "Parameter 2");

关于javascript - 在运行功能之前检查条件的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50132697/

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