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.pswp.cn/news/540734.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/540734.shtml
英文地址,請注明出處:http://en.pswp.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…