簡體   English   中英

monkeypatch導出函數

[英]monkeypatch exported function

nodev4運行 -

假設我有2個庫: foobar

foo有這個

var bar = require('./lib/bar');
exports = module.exports = function myApp(options) {
 [snip]
}
exports bar = bar;

bar有這個

module.exports = function doStuff(moreOptions) {
  function doMoreStuff () {
  }
}

我的應用程序了

x = requires(foo); 

我想做的是讓我的應用程序對doMoreStuff函數進行修補-這可能嗎?

我嘗試了各種庫,但我懷疑我對js的理解存在根本問題;)

讓我們看看你在這里有什么。

x = requires(foo);

你基本上有以下幾點

x = function (options){ /* function work */ }
x.bar = function(moreOptions){
    function doMoreStuff(){
    }
}

這雖然不是“非法的”,但很奇怪。 它相當於

a = function() { return "I'm a function"; }
a.bar = "I'm a string attached to a function";

console.log(a());   // => "I'm a function"
console.log(a.bar); // => "I'm a string attached to a function"

您的bar模塊的作用不大。 該函數包含一個不可訪問的函數。 讓我們假設你的意思

module.exports = function(moreOptions){
    return {
        doMoreStuff: function(){
            return "Bar doing more stuff";
        }
    }
}

如果你想新建一個myApp並附加一個外部函數,你會想

function myApp(options){

}
myApp.prototype.bar = bar();        // since you exported a function
module.exports = myApp;

在你的主應用程序中,你現在可以

x = require('foo');

var app = new foo();    // you MUST otherwise you get an empty function
app.bar.doMoreStuff();  // => "Bar doing more stuff"

另外(也不太容易出錯)foo可能是

var bar = require('bar');
module.exports = function (options) {
  // work here ...
  return {
    bar: bar(),    // again, exported as function
    appOptions: options,
    // ...
  }
}

然后在主模塊中

x = require('foo');
x.bar.doMoreStuff();   // => "Bar doing more stuff";

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM