Node中的javascript

在浏览器里面引用第三方的API,常常通过引用url加载,暴露出一个全局,比如jQuery,underscore等,造成这种原因是因为javascript中并没有为模块依赖以及模块独立定义设定专门的API。而Node里面提供了三个核心的全局对象来支持模块系统:require , exports , module.在node环境中输出即可查看详情.

require

  函数用于在当前模块中加载和使用其他模块 
     引用npm 下载的模块 或 node_module里面的模块

  var colors = require('colors');
  var a = require('./a');
  var b = require('./b');
  var data = require('./data.json');

  

exports

  exports对象是当前模块的导出对象,用于导出模块公有方法和属性。别的模块通过require函数使用当前模块时得到的就是当前模块的exports对象。以下例子中导出了一个公有方法.exports是module.exports的一个引用,默认情况下是一个对象

exports.name = 'This is a test demo';
exports.hello = function(){
  console.log('hello world');
}

module:

通过module对象可以访问到当前模块的一些相关信息,但最多的用途是重写对象,下面一个简单的构造器:

function A(options){
    this.name = options.name;
    this.age = options.age;
}
A.prototype.constructor = A;
A.prototype.doAction = function(){
    console.log('My name is ' + this.name);
}

module.exports = A;

学习参考资料:

http://nqdeng.github.io/7-days-nodejs/

<了不起的NodeJS>第四章

如有错误,请及时提出,QQ:470486732 

原文地址:https://www.cnblogs.com/w3cjiangtao/p/3633246.html