2017-10-06 46 views
1

我試圖理解快遞JS來源,這就是快遞出口無法理解這種快速JS源代碼片段

module.exports = createApplication; 


function createApplication() { 
    var app = function(req, res, next) { 
    app.handle(req, res, next); 
    }; 

    mixin(app, EventEmitter.prototype, false); 
    mixin(app, proto, false); 

    // expose the prototype that will get set on requests 
    app.request = Object.create(req, { 
    app: { configurable: true, enumerable: true, writable: true, value: app } 
    }) 

    // expose the prototype that will get set on responses 
    app.response = Object.create(res, { 
    app: { configurable: true, enumerable: true, writable: true, value: app } 
    }) 

    app.init(); 
    return app; 
} 

我感到困惑這段代碼

var app = function(req, res, next) { 
    app.handle(req, res, next); 
    }; 

主模塊變量app同時在函數內部分配和使用。這如何工作?其他地方沒有定義app。找到真正的來源here

回答

2

該功能已創建並分配給app變量。這是一個正常的函數表達式分配。

然後,兩條mixin()行將方法添加到app函數中。所以,在調用這些函數之後,它有諸如app.handle()app.init()之類的東西。

然後,再添加兩個屬性app.requestapp.response

然後,調用app.init()

然後,在某個時候調用app函數(當一個http請求到達時)以及調用該函數時,它調用app.handle(),它只調用一個屬性本身的函數。這都是合法的。這與在更傳統的對象中調用this.handle()類似。

這裏,似乎有你最困惑的部分有點演示:

var test = function() { 
 
    test.doSomething(); 
 
} 
 

 
test.doSomething = function() { 
 
    console.log("doSomething"); 
 
} 
 

 
test(); // causes test.doSomething() to get called

+0

哦,是的。現在有道理。謝謝! –