昨天我们讲解了如何 import 和 export 一个 modules,这时候你心中应该会有一个疑问,那如果假设这个 counter 档案里面有不同的东西,而我们也想一起使用他们呢?像下面的例子,我们又再多加了两个变数adder
和pi
,并且为了不要跟昨天混淆,将档名改成 stuff.js:
let counter = function(arr){
return `There are ${arr.length} elements in this array` ;
}
let adder = function(a, b){
return `The sum of 2 numbers are ${a + b}`
}
let pi = 3.14
事实上,这个module.exports
其实就是一个空的物件,我们可以用新增属性的方式把这个 module 里的变数一个一个加进去:
let counter = function(arr){
return `There are ${arr.length} elements in this array` ;
}
let adder = function(a, b){
return `The sum of 2 numbers are ${a + b}`
}
let pi = 3.14
module.exports.counter = counter
module.exports.adder = adder
module.exports.pi = pi
然後在 app.js import出来使用:
const stuff = require('./stuff')
console.log(stuff.counter([1,2,3,4,5])) // There are 6 elements in this array
console.log(stuff.adder(5,8)) // The sum of 2 numbers are 13
console.log(stuff.adder(stuff.pi, 5)) // The sum of 2 numbers are 8.14
除此之外,我们还有其他两种 export 方法:
法1:赋值直接加入 module.exports 的属性中:
module.exports.counter = function(arr){
return `There are ${arr.length} elements in this array` ;
}
module.exports.adder = function(a, b){
return `The sum of 2 numbers are ${a + b}`
}
module.exports.pi = 3.14
法2:使用物件
let counter = function(arr){
return `There are ${arr.length} elements in this array` ;
}
let adder = function(a, b){
return `The sum of 2 numbers are ${a + b}`
}
let pi = 3.14
module.exports = {
counter: counter,
adder: adder,
pi: pi
}
之後一样是用const stuff = require('./stuff')
import
透过 stuff.<属性名称>
的方式去取用
今天的 Module Patterns 就到此为止啦!
我们明天见
ㄅㄅ
React Component 只能透过资料状态的改变来更新画面,而 React 元件有两种资料来源...
在 React component 做资料 fetch、subscription、或手动改变 Rea...
今天事情比较多,没啥进度,就先对先前的内容补点漏洞。 登入 进站画面除了Day07的几个Patter...
前言:介绍完了二元树的建立和走访方式,紧接着要来介绍其他基本应用,一样用上一篇的程序码进行修改 可以...
嗨,我是 A Fei,来看看今天的题目: (题目来源:Codewars) Take the foll...