简体   繁体   English

从另一个函数内部调用变量很糟糕?

[英]Calling a variable from inside another function is bad?

I want to make my JS code to be less repetitive with an organized look.我想让我的 JS 代码以有组织的外观减少重复。 But I don't know if calling a function from inside another function is a bad practice, like Global Variables.但我不知道从另一个函数内部调用一个函数是否是一种不好的做法,比如全局变量。

I share a piece of the code here.我在这里分享一段代码。

thanks.谢谢。

 function getEx() { return document.getElementById('example') } function getExTwo() { return document.getElementById("exampleTwo"); } function getTheValue() { let getExValue = getEx(); let getExTwoValue = getExTwo(); }

Calling a function from within another function is absolutely not bad coding.从另一个函数中调用一个函数绝对是不错的编码。 That's part of what functions are for, really -- breaking up logical processes into smaller pieces.这就是功能的一部分,实际上——将逻辑过程分解成更小的部分。

Here's an example of how this can work.这是一个如何工作的示例。

// Note: This is new ES6/ES7 syntax for writing JavaScript functions.
// I'm using it here because it's very terse.

const add = (a, b) => a + b;

const multiply = (a, b) => a * b;

const square = (a) => multiply(a, a);

const sumOfSquares = (arr) => {
  let sum = 0;
  arr.forEach(number => sum += square(number));
  return sum;
};

In the (simplified) example above, we use different functions to break up the distinct logical pieces of the problem into smaller, more manageable problems.在上面的(简化的)示例中,我们使用不同的函数将问题的不同逻辑部分分解为更小、更易于管理的问题。 For example, to calculate the sum of the squares of the array [1, 10, 12] , we want to be able to add things and we want to be able to square things, so it's a good idea to create functions for performing each of those steps.例如,要计算数组[1, 10, 12]的平方和,我们希望能够添加事物并且我们希望能够对事物进行平方,因此创建用于执行每个的函数是个好主意这些步骤。 We might even want to use other functions within those functions (eg calling multiply from within square ).我们甚至可能想在这些函数中使用其他函数(例如从square调用multiply )。

Now, is it possible to go overboard with creating new functions?现在,是否有可能过度创建新功能? Yes.是的。 Try to avoid writing multiple functions that are basically the same.尽量避免编写多个基本相同的函数。 But otherwise... go nuts!但除此之外……发疯!

Calling a function from within another function is not bad.从另一个函数内部调用一个函数也不错。 It is a recommended way of reducing repetition by breaking your code into smaller pieces, each handling some specific logic.这是一种通过将代码分解成更小的部分来减少重复的推荐方法,每个部分都处理一些特定的逻辑。 Here is a simplified version of your code:这是您的代码的简化版本:

// ps: $ is not from jquery it is just a normal variable.
const $ = document.querySelector

const getValues = () => {
  const firstVal = $('#example')
  const secondVal = $('#exampleTwo')
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM