简体   繁体   English

从Javascript模块中的父作用域继承变量

[英]Inheriting variables from parent scope in Javascript Modules

I'm working with Webpack modules to keep things organized in my projects, but something very annoying is having to explicitly specify all the variables that the module might need, instead of just having it search for them in the calling function's scope. 我正在使用Webpack模块来使项目保持井井有条,但是很烦人的是必须明确指定模块可能需要的所有变量,而不仅仅是让它在调用函数的作用域中进行搜索。 Is there a better way to do it? 有更好的方法吗? Example: 例:

main.js main.js

import {logMonth} from "./helpers";

document.addEventListener("DOMContentLoaded", () => {
  let month = "September";
  logMonth();
});

helpers.js helpers.js

let logMonth = () => {
  console.log(month)
}

This will produce an error since logMonth() doesn't have access to the month variable. 由于logMonth()无法访问month变量,因此将产生错误。

This is an extremely simplified example, but for functions that need many variables, it can get pretty ugly to pass all the required arguments that the function might need. 这是一个极为简化的示例,但是对于需要许多变量的函数,传递函数可能需要的所有必需参数会变得非常难看。

My question is: Is there a way to make modules have access to the variables of the calling scope instead of explicitly passing them? 我的问题是:有没有一种方法可以使模块可以访问调用范围的变量,而不是显式地传递它们?

You could, but why would you want to? 您可以,但是为什么要这么做? Modules are designed to prevent this. 模块被设计为防止这种情况。 Always prefer pure functions, it's way easier to debug once the app becomes complicated. 始终喜欢纯函数,一旦应用变得复杂,它的调试方式就更容易。 Then you don't want to be searching multiple nested scopes from multiple modules for a bug, optimally you want to only be looking in the module that threw the error instead of every scope it has access to. 然后,您不想从多个模块中搜索多个嵌套作用域来查找错误,最佳情况下,您只希望查找引发错误的模块,而不是它可以访问的每个作用域。

So logMonth = month => console.log( month ); 所以logMonth = month => console.log( month ); and logMonth( 'September' ); logMonth( 'September' ); is preferred. 是首选。

You can use an object if you need to send multiple parameters to a function. 如果需要向一个函数发送多个参数,则可以使用一个对象。 That way you do not have to change the function call signature in all places, you just add another (optional) parameter to the object: 这样,您不必在所有位置都更改函数调用签名,只需向对象添加另一个(可选)参数:

logMonths = ({ year, month, day}) => { ...do stuff... }

This will work both with logMonths({ month: 'september' }) as with logMonths({ month: 'september', year: '2019' }) , so you never have to change like logMonths( 'september' ) into logMonths( null, 'september' ) and logMonths( 2019, 'september' ) everywhere you used logMonths() before it had a year parameter. 这对logMonths({ month: 'september' })logMonths({ month: 'september', year: '2019' }) ,因此您不必像logMonths( 'september' )一样更改为logMonths( null, 'september' )logMonths( 2019, 'september' )在使用year之前使用logMonths()的任何地方。

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

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