javascript模块_JavaScript中的模块

javascript模块

JavaScript模块 (JavaScript Modules)

One of the key features of programming fundamentals is breaking down your code into fragments. These fragments depending on its functionality have been coined various terms like functions, components, modules, etc. Today we'll understand what modules are, why they are needed and how to create modules in JavaScript?

编程基础知识的关键特征之一就是将您的代码分解为多个片段。 这些片段取决于其功能,是用不同的术语创造的,例如功能,组件,模块等。今天,我们将了解什么是模块 ,为什么需要它们以及如何在JavaScript中创建模块?

Imagine you're working on an application that seamlessly gets bigger and bigger in terms of lines of code. Of course, the first thing you did was create that hefty code a bit modular by breaking it down in functions. Good, but now you have a lot of functions. Wouldn't it make sense to organize your code into different scripts? These scripts are called "modules". You're dividing your script into numerous other scripts to keep the code more modular and organized. Modularity is a key concept for object-oriented programming too and it sort of follows the same pattern.

想象一下,您正在开发的应用程序在代码行方面可以无缝地变得越来越大。 当然,您要做的第一件事就是通过按功能分解将大量代码模块化。 很好,但是现在您有很多功能。 将代码组织成不同的脚本是否有意义? 这些脚本称为“模块” 。 您正在将脚本划分为许多其他脚本,以保持代码更加模块化和更有条理。 模块化也是面向对象编程的关键概念,它遵循相同的模式。

The three major advantages of Modules in JavaScript are maintainability which simply distributed codebase, Namespacing which implies that unrelated code do not share global variables and reusability, which is quite self-explanatory. That piece of code can be reused for other projects too.

JavaScript模块的三个主要优点是可维护性 ,它简单地分布在代码库中; Namespacing ,它表示不相关的代码不共享全局变量和可重用性 ,这是不言而喻的。 这段代码也可以重用于其他项目。

The first way of writing modular JS is using closures.

编写模块化JS的第一种方法是使用闭包。

Closures help us create anonymous functions and hide variables from parent scope. We can use local variables inside our function without collision with the same variables (having same name) outside because of their scope.

闭包可以帮助我们创建匿名函数,并在父范围内隐藏变量。 我们可以在函数内部使用局部变量,而不会因范围而与外部的相同变量(具有相同的名称)发生冲突。

<script>
	(function() {
		// We keep these variables private 
		// inside this closure scope
		var HP = [10, 40, 87, 66, 45, 90];

		var defeating = function() {
			var defeated = HP.filter(function(item) {
				return item < 50;
			});
			return 'You were defeated ' + defeated.length + ' times.';
		}
		console.log(defeating());
	}()); 
</script>

Output

输出量

You were defeated 3 times.

Another approach is to create modules using an object like interface. Let's modify the above code only,

另一种方法是使用类似接口的对象创建模块 。 让我们只修改上面的代码,

const pokebattle=(function () {
	var HP = [10, 40, 87, 66, 45, 90];
	return{
		defeating: function(){
			var defeated = HP.filter(function(item) {
				return item < 50;});
				return 'You were defeated ' + defeated.length + ' times.';
			}
		}
	}());    
	console.log(pokebattle.defeating());
</script>

Output

输出量

You were defeated 3 times.

使用CommonJS (Using CommonJS)

Using CommonJS, we can have each script as a module and use the keywords module.exports to export a module and require to import them.

使用CommonJS ,我们可以将每个脚本作为一个模块,并使用关键字module.exports导出模块并要求导入它们。

function Pokemon() {
    this.greet = function() {
        return 'Hey this is squirtle';
    }

    this.catchPhrase = function() {
        return 'Squirtle Squirtle';
    }
}

module.exports = Pokemon;

And when someone wants to use our pokemon module inside their local js file they can simply do,

当有人想在他们的本地js文件中使用我们的pokemon模块时,他们可以轻松地做到这一点,

var pokeModule = require('Pokemon');
var pokeInstance = new Pokemon();

pokeInstance.greet();
pokeInstance.catchphrase();

Output

输出量

Hey this is squirtle
Squirtle Squirtle 

Most web frameworks make use of modules extensively. If you have used Node.Js ever you must have noticed very frequently you're importing a module from the core Node.js and then using it. For ex using the fs module for writing and reading from a file,

大多数Web框架广泛使用模块。 如果您曾经使用过Node.J,那么您一定会非常频繁地注意到您是从核心Node.js导入模块,然后再使用它。 例如,使用fs模块进行文件读写时,

    const fs=require('fs');

The above syntax states that you're importing a node module called fs inside the fs variable so now you can use it anywhere in that file.

上面的语法表明您正在fs变量中导入名为fs的节点模块,因此现在可以在该文件中的任何位置使用它。

Or if you use express to create a server in Node.js,

或者,如果您使用express在Node.js中创建服务器,

const express = require('express');
const app = express();
app.listen(3000, () => {
    console.log('Listening on port 3000...');
});

If you've worked with frontend frameworks like Angular, Vue or React; the modular code pattern is the crux behind their component based architecture. In fact, the first few lines you write every time you're coding in React are,

如果您使用过Angular,Vue或React等前端框架, 模块化代码模式是其基于组件的体系结构背后的关键。 实际上,您每次在React中编写代码时,前几行就是

    Import React, {Component} from 'React';

Thus modular patterns are very widely used today and almost everywhere. Massive libraries that utilise and make packages for JS are also modules. We have packages for bundling these modules like Webpack.

因此,模块化模式在当今以及几乎所有地方都得到了广泛的使用。 利用和制作JS软件包的大量库也是模块。 我们有捆绑这些模块的软件包,例如Webpack。

翻译自: https://www.includehelp.com/code-snippets/modules-in-javascript.aspx

javascript模块

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值