【问题标题】:Where does the "exports" define in PhantomJS? [duplicate]PhantomJS 中的“出口”在哪里定义? [复制]
【发布时间】:2016-09-13 11:02:01
【问题描述】:

fs.js的一段代码为例:

exports.write = function (path, content, modeOrOpts) {
    var opts = modeOrOptsToOpts(modeOrOpts);
    // ensure we open for writing
    if ( typeof opts.mode !== 'string' ) {
        opts.mode = 'w';
    } else if ( opts.mode.indexOf('w') == -1 ) {
        opts.mode += 'w';
    }
    var f = exports.open(path, opts);

    f.write(content);
    f.close();
};

现在我对exports 对象感到困惑。你可以在每个 PhantomJS 模块中找到它,但我找不到在哪里定义 exports 对象。

谁能给我一些关于定义exports对象的地方的建议?


不要与 NodeJS 中的 exports 混淆。它是 PhantomJS...

【问题讨论】:

标签: javascript phantomjs


【解决方案1】:

phantomJS 实现了require 语法(与NodeJS 相同)

如果你想包含外部库,该库被注入@​​987654324@ 对象,module.exports 是 require 函数返回的公共对象。

//myMoudle.js

var _a = 5; //this is private member of the module 

module.exports= {
    a : ()=>{
      return _a;
    },
    setA : newA=>_a=newA;
}

要求:

//someCode.js
var myModule = require('path/to/myModule')
myModule.a() //5
myModule._a //undefined
myModule.setA(6) //_a is now 6

PhantomJS 文档示例 requiring webpage module:

var webPage = require('webpage'); //included the module https://github.com/ariya/phantomjs/blob/master/src/modules/webpage.js 
var page = webPage.create();

包含webPage模块,在这个模块里面有下一段代码

exports.create = function (opts) {
    return decorateNewPage(opts, phantom.createWebPage());
};

允许在我们使用 require 函数的地方使用 webPage.create 函数

【讨论】:

  • "实现的 phantomJS 需要语法",你能告诉我实现 require 语法的 PhantomJS 中的代码吗?
  • @Sayakiss 添加到我的回答中
  • 我还是一头雾水……在我看来,require 是一个函数,所以应该在某个地方定义它(但我找不到)……exports 是一个对象,所以它应该在某个地方定义(但我也找不到)......这才是真正困扰我的......
  • @Sayakiss 模块是一个由编译器注入到你的模块中的对象(JS 没有编译器,它是解释器,但是 nvm),就像浏览器中的windowmodule.exports 是对象从require操作返回的
  • @Sayakiss 将其视为class 而不是public 你写的exportspublic func foo() 变为 exports.foo = function,其余为私有(但都是静态的,如果多次需要同一个模块,则只创建一次)
猜你喜欢
  • 1970-01-01
  • 2017-11-25
  • 2018-02-15
  • 2021-11-05
  • 1970-01-01
  • 2012-05-02
  • 1970-01-01
  • 2012-10-13
  • 2018-04-23
相关资源
最近更新 更多