CommonJs 모듈시스템에서의 "module.exports"와 "exports"의 차이점
이 페이지(http://docs.nodejitsu.com/articles/getting-started/what-is-require),에는 export 객체를 함수 또는 새 객체로 설정하는 경우 module.discover 객체를 사용해야 합니다.)라고 기재되어 있습니다.
내 질문은 왜?
// right
module.exports = function () {
console.log("hello world")
}
// wrong
exports = function () {
console.log("hello world")
}
결과.log)를 기록했습니다.result=require(example.js)
), 첫 가 '일부러'입니다[Function]
는 두두 the the입니다.{}
.
그 이유를 설명해 주시겠습니까?여기서 'module.exports vs exports in Node.js'라는 글을 읽었습니다.이것은 도움이 되지만, 왜 그렇게 설계되었는지는 설명되지 않습니다.수출 레퍼런스를 직접 반송하면 문제가 발생합니까?
module
는 JavaScript를 입니다.exports
★★★★★★★★★★★★★★★★★★.exports
이며, JavaScript로 됩니다.module.exports
node.'return'입니다.node.js는 'return'입니다.module.exports
require
파일을 은 다음과 노드에서 JS 파일을 표시하는 간단한 방법은 다음과 같습니다.
var module = { exports: {} };
var exports = module.exports;
// your code
return module.exports;
속성을 exports
,맘에 들다exports.a = 9;
「 」를합니다.module.exports.a
오브젝트는 JavaScript에서 참조로 전달되기 때문에 여러 변수를 같은 오브젝트로 설정하면 모두 같은 오브젝트입니다.exports
★★★★★★★★★★★★★★★★★」module.exports
같은 객체입니다.
, <<고객명>>을 했을 경우exports
는, 더 「신규」 「신규」 「신규」 「신규」 「신규」로 설정되지 .module.exports
, (그래서)exports
★★★★★★★★★★★★★★★★★」module.exports
더 이상 같은 객체가 아닙니다.
르네의 대답은 잘 설명되었다.예를 들어 답변에 추가:
노드는 파일에 많은 작업을 수행하며 중요한 작업 중 하나는 파일을 래핑하는 것입니다.내부 nodejs 소스 코드 "module.exports"가 반환됩니다.한 걸음 물러서서 포장지를 이해합시다.예를 들어
greet.greet.matrix 를 클릭합니다.
var greet = function () {
console.log('Hello World');
};
module.exports = greet;
위의 코드는 다음과 같이 nodejs 소스 코드 내에서 IIE(Imediate Regived Function Expression)로 래핑됩니다.
(function (exports, require, module, __filename, __dirname) { //add by node
var greet = function () {
console.log('Hello World');
};
module.exports = greet;
}).apply(); //add by node
return module.exports; //add by node
위의 함수는 (.syslog()) 호출되어 module.syslog가 반환됩니다.이 시점에서 module.은 같은 참조를 나타내는 export와 export를 실시합니다.
이제 greet.js를 greet.js로 다시 쓴다고 가정해 봅시다.
exports = function () {
console.log('Hello World');
};
console.log(exports);
console.log(module.exports);
출력은 다음과 같습니다.
[Function]
{}
이유는 module.module은 빈 객체입니다.module.function에 아무것도 설정하지 않고 exports = function().....을 새 greet.function으로 설정했습니다.module.exports가 비어 있습니다.
기술적으로는 exports와 module.exports가 동일한 참조를 가리켜야 합니다(thats rect!!).그러나 export에 function()...을 할당할 때는 "="를 사용합니다.이것에 의해, 메모리에 다른 오브젝트가 생성됩니다.따라서 module.export와 export의 결과는 다릅니다.수출에 관한 한 우리는 그것을 무시할 수 없다.
이제 greet.js(Renee answer를 참조)를 다음과 같이 다시 쓴다고 가정해 보겠습니다.
exports.a = function() {
console.log("Hello");
}
console.log(exports);
console.log(module.exports);
출력은 다음과 같습니다.
{ a: [Function] }
{ a: [Function] }
보시는 바와 같이 module.exports와 exports는 동일한 참조, 즉 함수를 가리키고 있습니다.내보내기 속성을 설정하면 JS에서는 객체가 참조로 전달되기 때문에 module.exports로 설정됩니다.
결론은 혼란을 피하기 위해 항상 module.exports를 사용합니다.이게 도움이 됐으면 좋겠다.해피 코딩 :)
또한 다음 사항을 이해하는 데 도움이 될 수 있습니다.
math.matrix
this.add = function (a, b) {
return a + b;
};
client.displaces를 설정합니다.
var math = require('./math');
console.log(math.add(2,2); // 4;
좋아요, 이 경우:
console.log(this === module.exports); // true
console.log(this === exports); // true
console.log(module.exports === exports); // true
따라서 디폴트로는 "this"는 실제로는 module.exports와 동일합니다.
다만, 실장을 다음과 같이 변경했을 경우는,
math.matrix
var add = function (a, b) {
return a + b;
};
module.exports = {
add: add
};
이 경우 정상적으로 동작하지만 새로운 오브젝트가 생성되었기 때문에 "this"는 module.exports와 동일하지 않습니다.
console.log(this === module.exports); // false
console.log(this === exports); // true
console.log(module.exports === exports); // false
이제 require에 의해 반환되는 것은 module.exports 내에서 정의된 내용입니다.이것도 export도 아닙니다.
또 다른 방법은 다음과 같습니다.
math.matrix
module.exports.add = function (a, b) {
return a + b;
};
또는 다음 중 하나를 선택합니다.
math.matrix
exports.add = function (a, b) {
return a + b;
};
이이의 rene rene rene rene rene rene rene rene rene rene rene rene rene rene rene 의 관계에 대한 르네의 대답exports
★★★★★★★★★★★★★★★★★」module.exports
꽤 명확합니다. 모두 자바스크립트 레퍼런스에 관한 것입니다. 싶은이 있습니다.
이는 많은 노드모듈에서 볼 수 있습니다.
var app = exports = module.exports = {};
이렇게 하면 module.exports를 변경해도 두 변수가 동일한 개체를 가리키도록 함으로써 내보내기를 계속 사용할 수 있습니다.
노드의 동작은 다음과 같습니다.
module.exports = exports = {}
module.module과 export는 같은 오브젝트를 참조합니다.
이것은 단지 편의상 행해지는 것이다.그래서 이렇게 쓰는 대신
module.exports.PI = 3.14
우리는 쓸 수 있다
exports.PI = 3.14
따라서 내보내기에 속성을 추가할 수는 있지만 다른 개체에 할당하는 것은 허용되지 않습니다.
exports.add = function(){
.
.
}
↑ 이는 module.dev.add = function()과 동일하며 정상입니다.}
exports = function(){
.
.
}
↑ 이는 정상이 아니며 module.module은 여전히 {}을(를) 참조하고 내보내기는 다른 개체를 참조하므로 빈 개체가 반환됩니다.
이 있다module.exports
★★★★★★★★★★★★★★★★★」exports
단일 클래스, 변수 또는 함수를 한 모듈에서 다른 모듈로 내보낼 때는
module.exports
그러나 모듈 간에 여러 변수 또는 함수로 내보내려면exports
.module.exports
는 require() 콜에서 반환되는 오브젝트 참조입니다.그렇지만exports
require에 의해 반환되지 않습니다.
자세한 것은, 예를 참조해 주세요.>> 링크
위의 답변은 모두 잘 설명되어 있기 때문에, 저는 오늘 직면했던 것을 덧붙이고 싶습니다.
내보내기를 사용하여 무언가를 내보낼 때는 변수와 함께 사용해야 합니다.맘에 들다,
파일 1.js
exports.a = 5;
다른 파일
파일 2.js
const A = require("./File1.js");
console.log(A.a);
module.module을 사용합니다.
파일 1.js
module.exports.a = 5;
파일2.js의 경우
const A = require("./File1.js");
console.log(A.a);
및 디폴트 module.displays
파일 1.js
module.exports = 5;
파일2.js의
const A = require("./File2.js");
console.log(A);
myTest.js
module.exports.get = function () {};
exports.put = function () {};
console.log(module.exports)
// output: { get: [Function], put: [Function] }
exports
그리고.module.exports
는 동일하며 동일한 오브젝트에 대한 참조입니다.필요에 따라 두 가지 방법으로 속성을 추가할 수 있습니다.
export는 특정 모듈 내의 module.exports에 대한 숏컷이라고 생각할 수 있습니다.실제로 내보내기란 모듈을 평가하기 전에 module.exports 값으로 초기화되는 변수일 뿐입니다.이 값은 객체(이 경우 빈 객체)에 대한 참조입니다.즉, exports는 module.exports가 참조하는 동일한 오브젝트에 대한 참조를 보유하고 있습니다.또한 내보내기에 다른 값을 할당하면 module.exports에 바인딩되지 않게 됩니다.
MDN의 설명이 가장 명확합니다.
기본적으로 메모리에는 exports와 module.exports라는2개의 변수에 의해 참조되는 오브젝트가1개 있어요
exports.a = 23
동등.
module.exports = {a:23}
그렇지만,
exports = {a:23}
동일하지 않다
module.exports = {a:23}
새 개체를 할당하는 경우exports
변수 직접, 그 변수가 참조하지 않습니다.module.exports
더이상.
언급URL : https://stackoverflow.com/questions/16383795/difference-between-module-exports-and-exports-in-the-commonjs-module-system
'programing' 카테고리의 다른 글
Larabel - 요청에 따라 세션 저장소가 설정되지 않음 (0) | 2023.01.25 |
---|---|
MySQL 오류 1264: 열의 값을 벗어났습니다. (0) | 2023.01.25 |
하나의 캐치 블록에서 여러 예외 유형 포착 (0) | 2023.01.25 |
JavaScript로 리다이렉트하려면 어떻게 해야 하나요? (0) | 2023.01.25 |
Selenium Web 드라이버 및 Java.요소(x, y)는 점(x, y)에서 클릭할 수 없습니다.다른 요소는 클릭을 받습니다. (0) | 2023.01.25 |