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模块

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/540734.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

在mac上安装Docker

1.进入一下地址进行下载docker https://download.docker.com/mac/stable/Docker.dmg 进入后进行下载后进行安装 2.将其拖动到Appliaction中即可 3.第一打开会有一个这样的欢迎页面 3.检查是否安装完成 出现上图所示标示安装完成了

composer 检查镜像_检查N元树中的镜像

composer 检查镜像Problem statement: 问题陈述&#xff1a; Given two n-ary trees, the task is to check if they are mirrors of each other or not. 给定两个n元树&#xff0c;任务是检查它们是否互为镜像。 Note: you may assume that root of both the given tree as …

浪潮各机型前面板指示灯含义

NF560D2 NF3020M2 NF5020M3 NF5140M3 NF5212H2 NF5220 NF5224L2 NF5240M3 NF5270M3 NF5280M2 NF5280M3 NF5540M3 NF5580M3 NF8420M3 NF8520 NF8560M2 说明&#xff1a;转浪潮官网。

python dll 混合_Python | 条线混合图

python dll 混合In some of the cases, we need to plot a bar-line hybrid plot. This plot helps in a better understanding of dynamics as well as the relative magnitude of each point in the plot. Bar-Line Hybrid Plots are mostly used for the representation of …

测试八 赛后感受

测试八 当我打开T1的时候&#xff0c;就没有往下看题目了&#xff0c;主要是发现T1就是之前做过&#xff0c;而且我也看过题解的题目&#xff0c;接着就开始钻研&#xff0c;当然&#xff0c;也没什么好钻研的&#xff0c;大概思路还是知道的&#xff0c;再写写数据就已经很清晰…

推荐五个免费的网络安全工具

导读&#xff1a; 在一个完美的世界里&#xff0c;信息安全从业人员有无限的安全预算去做排除故障和修复安全漏洞的工作。但是&#xff0c;正如你将要学到的那样&#xff0c;你不需要无限的预算取得到高质量的产品。这里有SearchSecurity.com网站专家Michael Cobb推荐的五个免费…

bios部署模式审核模式_BIOS的完整形式是什么?

bios部署模式审核模式BIOS&#xff1a;基本输入输出系统 (BIOS: Basic Input Output System) BIOS is an abbreviation of the Basic Input Output System. In the beginning, when you first set on your computer, the first software which starts run by the computer is &…

day04-装饰器

一、装饰器定义 1&#xff09;装饰器&#xff1a;本质是函数。 2&#xff09;功能&#xff1a;用来装饰其他函数&#xff0c;顾名思义就是&#xff0c;为其他的函数添加附件功能的。 二、原则 1&#xff09;不能修改被装饰函数的源代码 2&#xff09;不能修改被装饰函数的调用方…

c 语言bool 类型数据_C ++中的bool数据类型

c 语言bool 类型数据In C programming language, to deal with the Boolean values – C added the feature of the bool data type. A bool variable stores either true (1) or false (0) values. 在C 编程语言中&#xff0c;为了处理布尔值– C 添加了bool数据类型的功能 。…

C ++中的std :: binary_search()

binary_search()作为STL函数 (binary_search() as a STL function) Syntax: 句法&#xff1a; bool binary_search (ForwardIterator first, ForwardIterator last, const T& value);Where, 哪里&#xff0c; ForwardIterator first iterator to start of the range For…

HNUSTOJ-1437 无题

1437: 无题 时间限制: 1 Sec 内存限制: 128 MB提交: 268 解决: 45[提交][状态][讨论版]题目描述 tc在玩一个很无聊的游戏&#xff1a;每一次电脑都会给一个长度不超过10^5的字符串&#xff0c;tc每次都从第一个字符开始&#xff0c;如果找到两个相邻相一样的字符&#xff0c;…

凯撒密码pythin密码_凯撒密码术

凯撒密码pythin密码Caesar cipher is one of the well-known techniques used for encrypting the data. Although not widely used due to its simplicity and being more prone to be cracked by any outsider, still this cipher holds much value as it is amongst the fir…

MultiQC使用指导

MultiQC使用指导 官网资料文献&#xff1a;MultiQC --- summarize analysis results for multiple tools and samples in a single report参考资料一&#xff1a; 整合 fastq 质控结果的工具 简介 MultiQC 是一个基于Python的模块, 用于整合其它软件的报告结果, 目前支持以下软…

FYFG的完整形式是什么?

FYFG&#xff1a;对您的未来指导 (FYFG: For Your Future Guidance) FYFG is an abbreviation of "For Your Future Guidance". FYFG是“ For your Future Guidance”的缩写 。 It is an expression, which is commonly used in the Gmail platform. It is also wr…

WorkerMan 入门学习之(二)基础教程-Connection类的使用

一、TcpConnection类 的使用 1、简单的TCP测试 Server.php <?php require_once __DIR__./Workerman/Autoloader.php; use Workerman\Worker; $worker new Worker(websocket://0.0.0.0:80);// 连接回调 $worker->onConnect function ($connection){echo "connecti…

kotlin获取属性_Kotlin程序获取系统名称

kotlin获取属性The task is to get the system name. 任务是获取系统名称。 package com.includehelpimport java.net.InetAddress/*** Function for System Name*/fun getSystemName(): String? {return try {InetAddress.getLocalHost().hostName} catch (E: Exception) {S…

71文件类型

1.kit类型 标准的SeaJs模块文件类型&#xff0c;直接对外暴露方法。 2.units类型 依赖pageJob&#xff0c;对外暴露一个名字&#xff0c;pageJob依赖暴露的名字对模块进行初始化&#xff0c;在pageJob内部逻辑自动执行init方法&#xff1b; 由于没有对外暴露方法&#xff0c;只…

ruby 生成哈希值_哈希 Ruby中的运算符

ruby 生成哈希值In the last article, we have seen how we can carry out a comparison between two hash objects with the help of "" operator? "" method is a public instance method defined in Ruby’s library. 在上一篇文章中&#xff0c;我们看…

七牛大数据平台的演进与大数据分析实践--转

原文地址&#xff1a;http://www.infoq.com/cn/articles/qiniu-big-data-platform-evolution-and-analysis?utm_sourceinfoq&utm_mediumpopular_widget&utm_campaignpopular_content_list&utm_contenthomepage 七牛大数据平台的演进与大数据分析实践 (点击放大图像…

最大化切割段

Description: 描述&#xff1a; In this article we are going to review classic dynamic programing problem which has been featured in interview rounds of amazon. 在本文中&#xff0c;我们将回顾在亚马逊的采访轮次中已经介绍的经典动态编程问题。 Problem statemen…