programing tip

Node.js-생성자로 module.exports 사용

itbloger 2020. 7. 28. 08:03
반응형

Node.js-생성자로 module.exports 사용


Node.js 매뉴얼에 따르면 :

모듈 내보내기의 루트를 생성자 등의 함수로 만들거나 한 번에 하나의 속성을 작성하는 대신 하나의 할당으로 전체 객체를 내보내려면 내보내기 대신 module.exports에 할당하십시오. .

주어진 예는 다음과 같습니다.

// file: square.js
module.exports = function(width) {
  return {
    area: function() {
      return width * width;
    }
  };
}

그리고 이런 식으로 사용 :

var square = require('./square.js');
var mySquare = square(2);
console.log('The area of my square is ' + mySquare.area());

내 질문 : 예제에서 square를 객체로 사용하지 않는 이유는 무엇입니까? 다음은 유효하며 예제를보다 "객체 지향"으로 만드는가?

var Square = require('./square.js');
var mySquare = new Square(2);
console.log('The area of my square is ' + mySquare.area());

CommonJS 모듈은 두 가지 방법으로 내 보낸 특성을 정의 할 수 있습니다. 두 경우 모두 Object / Function을 반환합니다. 함수는 JavaScript에서 일류 시민이기 때문에 객체처럼 작동 할 수 있습니다 (기술적으로 객체입니다). new키워드 사용에 대한 귀하의 질문 에는 간단한 답변이 있습니다. 예. 나는 설명 할 것이다 ...

모듈 수출

exports제공된 변수 를 사용하여 속성을 첨부 할 수 있습니다. 다른 모듈에서 필요한 속성을 할당 할 수있게됩니다. 또는 module.exports 속성에 객체를 할당 할 수 있습니다. 두 경우 모두로 반환되는 require()것은의 값에 대한 참조입니다 module.exports.

모듈 정의 방법의 의사 코드 예 :

var theModule = {
  exports: {}
};

(function(module, exports, require) {

  // Your module code goes here

})(theModule, theModule.exports, theRequireFunction);

위의 예에서 module.exportsexports같은 목적이다. 멋진 부분은 전체 시스템이 그것을 처리하기 때문에 CommonJS 모듈에서 아무것도 보지 못한다는 것입니다. 내보내기 속성과 내보내기 변수가있는 모듈 객체가 있다는 것을 알아야합니다. module.exports와 같은 기능입니다.

생성자 필요

함수를 직접 연결할 수 있기 때문에 module.exports본질적으로 함수를 반환 할 수 있으며 다른 함수와 마찬가지로 생성자 로 관리 할 수 ​​있습니다 (이 함수는 JavaScript에서 생성자와 함수의 유일한 차이점은 사용하려는 방법이기 때문에 기울임 꼴로 표시됩니다. 다른 점이 없다.)

따라서 다음은 완벽하게 좋은 코드이며 개인적으로 권장합니다.

// My module
function MyObject(bar) {
  this.bar = bar;
}

MyObject.prototype.foo = function foo() {
  console.log(this.bar);
};

module.exports = MyObject;

// In another module:
var MyObjectOrSomeCleverName = require("./my_object.js");
var my_obj_instance = new MyObjectOrSomeCleverName("foobar");
my_obj_instance.foo(); // => "foobar"

비 생성자 필요

Same thing goes for non-constructor like functions:

// My Module
exports.someFunction = function someFunction(msg) {
  console.log(msg);
}

// In another module
var MyModule = require("./my_module.js");
MyModule.someFunction("foobar"); // => "foobar"

In my opinion, some of the node.js examples are quite contrived.

You might expect to see something more like this in the real world

// square.js
function Square(width) {

  if (!(this instanceof Square)) {
    return new Square(width);
  }

  this.width = width;
};

Square.prototype.area = function area() {
  return Math.pow(this.width, 2);
};

module.exports = Square;

Usage

var Square = require("./square");

// you can use `new` keyword
var s = new Square(5);
s.area(); // 25

// or you can skip it!
var s2 = Square(10);
s2.area(); // 100

For the ES6 people

class Square {
  constructor(width) {
    this.width = width;
  }
  area() {
    return Math.pow(this.width, 2);
  }
}

export default Square;

Using it in ES6

import Square from "./square";
// ...

When using a class, you must use the new keyword to instatiate it. Everything else stays the same.


This question doesn't really have anything to do with how require() works. Basically, whatever you set module.exports to in your module will be returned from the require() call for it.

This would be equivalent to:

var square = function(width) {
  return {
    area: function() {
      return width * width;
    }
  };
}

There is no need for the new keyword when calling square. You aren't returning the function instance itself from square, you are returning a new object at the end. Therefore, you can simply call this function directly.

For more intricate arguments around new, check this out: Is JavaScript's "new" keyword considered harmful?


The example code is:

in main

square(width,function (data)
{
   console.log(data.squareVal);
});

using the following may works

exports.square = function(width,callback)
{
     var aa = new Object();
     callback(aa.squareVal = width * width);    
}

At the end, Node is about Javascript. JS has several way to accomplished something, is the same thing to get an "constructor", the important thing is to return a function.

This way actually you are creating a new function, as we created using JS on Web Browser environment for example.

Personally i prefer the prototype approach, as Sukima suggested on this post: Node.js - use of module.exports as a constructor

참고URL : https://stackoverflow.com/questions/20534702/node-js-use-of-module-exports-as-a-constructor

반응형