Skip to content

Instantly share code, notes, and snippets.

@externvoid
Last active August 5, 2018 07:20
Show Gist options
  • Select an option

  • Save externvoid/b9881fdfb535959da15b204867481504 to your computer and use it in GitHub Desktop.

Select an option

Save externvoid/b9881fdfb535959da15b204867481504 to your computer and use it in GitHub Desktop.
Node.jsのモジュール

オブジェクトのexport

sub.js

// exports = 999                                                                
module.exports.add = function() {
  var sum = 0, i = 0, args = arguments, l = args.length
  while(i < l) {
    sum += args[i++];
  }
  return sum
}
module.exports.inc= function() {
  var args = arguments
  return args[0] + 1
}
foo = 1234 // global object
baz = function() { // also global
  console.log("sub module")
}
var bar = 456

main.js

var add = require('./sub').add
// same above
// const { add } = require('./sub')
var inc = require('./sub').inc

console.log(add(1,2)) // => 3
console.log(inc(2)) // => 3
console.log(foo) // => 1234
console.log(global.foo) // => 1234
console.log(typeof bar) // => undefined

baz() // => sub module

もうイッチョ

class_def.js

module.exports = class Animal {
  constructor(baw) {
    this.baw = baw
  }
  say(){
    console.log(this.baw)
  }
}

import_class.js

const Animal = require('./class_def')                                           
var inu = new Animal('わんわん')
inu.say()

import/exportとの関係

ES6との関係 JavaScriptの標準化団体は2つ

  1. W3C
  2. WHATWG: Web Hypertext Application Technology Working Group, Apple + Mozilla + Operaのエンジニアにより作られる。 これも良さそう、全部読んで無いけど
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment