>  기사  >  백엔드 개발  >  js 내보내기에 대한 자세한 설명

js 내보내기에 대한 자세한 설명

小云云
小云云원래의
2018-03-31 16:36:5424557검색

이 글은 주로 코드 형식으로 js 내보내기에 대한 자세한 설명을 공유합니다.

관련 영상 추천: 1.JavaScript Quick Start_옥녀심경 시리즈
관련 매뉴얼 추천: 1.JavaScript 중국어 참고 매뉴얼

쓰기 1

exports.hello = function(){
    console.log(‘world’);
}

쓰기 2

var f = {
    hello : function(){
        console.log(‘world’);
    }
}
module.exports = f;

우리가 작성하는 모듈의 파일명이 hello.js라고 가정하고, 다음 코드를 실행합니다

var h = require(‘hello’);
h.hello();

위의 두 가지 작성 방법 모두 이 코드를 실행한 후의 결과는 같습니다.

module.exports:

예:

1,

//a.js
module.exports = ['aaa',18]
//b.js
var a= require('a')console.log(a[1]) //输出18

2,

//a.js
module.exports =function(){
this.show=function(){
console.log('hahah~');
}
}
//b.js
var a= require('a');
var obj = new a();obj .show();//输出hahah~
module.exports

제가 이해한 바는: module.exports에 할당한 것입니다. require 후에 무언가를 얻게 됩니다.

exports : 

//a.js
exports.show =function(){
console.log('hahah~');
}
//b.js
var a= require('a');
a.show();//输出hahah~

exports는 다음과 같습니다. 이미 객체입니다. 이 객체에 속성을 추가하면 내보내기 객체를 얻을 수 있습니다.

그러나 내보내기에 새 개체를 할당할 수는 없습니다(예: 내보내기={}

module.exports에 이미 콘텐츠가 있으면 내보내기의 모든 작업이 유효하지 않습니다.

프로토타입에 대해 이야기해 봅시다). 다시 프로토타입은 프로토타입에 속성을 추가하는 용도입니다. 프로토타입은 C++의 상위 클래스와 같습니다. 또 다른 예를 들어보겠습니다

//a.js
module.exports =function(){
}
module.exports.prototype.show = function(){
console.log('hahah~');
}
//b.js
var a= require('a');
var obj = new a()
obj.show()//输出hahah~

마지막으로 클래스 메소드에 대해 이야기하겠습니다. . 클래스의 경우 module.exports를 사용해야 합니다.

Chestnuts are here

1,


//a.js
module.exports =function(){
}
module.exports.show = function(){
console.log('hahah~');
}
//b.js
var a= require('a');
a.show()//输出hahah~
##module.exports与exports的区别

모든 node.js 실행 파일은 자동으로 모듈 객체를 생성합니다. 동시에 모듈 객체는 내보내기라는 속성을 생성하며 초기화된 값은 {}

module.exports = {};
Node.js为了方便地导出功能函数,node.js会自动地实现以下这个语句
foo.js
exports.a = function(){
console.log('a')
}
exports.a = 1 
test.js
var x = require('./foo');
console.log(x.a)

입니다. 이 시점에서 내보내기는 module.exports의 값을 참조한다는 답변을 모두 보셨을 것입니다.

module.exports가 변경되면 내보내기는 변경되지 않으며, 모듈을 내보낼 때 실제 내보내기 실행은 내보내기가 아닌 module.exports입니다.

다음 예를 다시 살펴보세요


foo.js
exports.a = function(){
 console.log('a')
}
module.exports = {a: 2}
exports.a = 1 
test.js
var x = require('./foo');
console.log(x.a)
result:
2

exports in module.exports 변경 후에는 무효가 됩니다.

조금 깨달음을 느끼기 시작하셨나요? 다음은 오픈 소스 모듈에서 흔히 볼 수 있는 몇 가지 사용 방법입니다.

##module.exports = View
function View(name, options) { 
  options = options || {};
  this.name = name;
  this.root = options.root;
  var engines = options.engines;
  this.defaultEngine = options.defaultEngine;
  var ext = this.ext = extname(name);
  if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no         extension was provided.');
  if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') +     this.defaultEngine);
  this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
  this.path = this.lookup(name);
}
module.exports = View;

JavaScript에는 함수는 객체, 뷰는 객체, module.export =View라는 말이 있는데 이는 전체 뷰 객체를 내보내는 것과 같습니다.

외부 모듈에서 호출하면 View의 모든 메서드를 호출할 수 있습니다. 그러나 프로토타입에 의해 생성된 메서드는 View의 정적 메서드만 호출할 수 있다는 점에 유의해야 합니다.


foo.js
function View(){
}
View.prototype.test = function(){
 console.log('test')
}
View.test1 = function(){
 console.log('test1')
}
module.exports = View
test.js
var x = require('./foo');
console.log(x) //{ [Function: View] test1: [Function] }
console.log(x.test) //undefined
console.log(x.test1) //[Function]
x.test1() //test1
##var app = exports = module.exports = {};

사실 원리를 이해하면 이런 작성 방식이 다소 중복된다는 점을 이해하기 어렵지 않습니다. 사실 모듈의 초기화 환경을 깨끗하게 유지하기 위한 것입니다. 동시에 module.exports가 가리키는 객체를 변경한 후에도 여전히 내보내기의 특성을 사용할 수 있습니다


exports = module.exports = createApplication;
/**
 * Expose mime.
 */
exports.mime = connect.mime;

예: module.exports = createApplication이 module.exports를 변경하고 내보내기를 무효화하고, 내보내기 = 모듈 내보내기 메서드를 전달하여 원래 특성을 복원합니다.

##exports.init= function(){}

가장 간단하고 직접 내보내는 모듈 초기화 방법입니다.

##var mongoose = module.exports =exports = new Mongoose;

하나에 여러 기능이 들어있지만 위의 설명만으로는 답을 얻으실 수 없을 것입니다.


위 내용은 js 내보내기에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.