2015-03-30 39 views
-1

使用NodeJS v0.12.1,在下文中,我試圖將外部文件讀入配置對象,並使用該對象提供的值執行一些測試。NodeJS:理解模塊中的變量範圍

我認爲config將在before函數的範圍內,但我得到before函數中第一行的錯誤ReferenceError: config is not definedbefore內爲什麼不能config

module.exports = { 
    config     : require('../../testconfig.json'), 
    before     : function (browser) { 
    pass = config.pass; 
    siteroot = config.local.address + config.local.subdir; 
    }, 
    after     : function (browser) { 
    //we'll come up with something later.... 
    }, 
    'Testing the Login page': function (browser) { 
    var greeting = 'Welcome, ' + user + '!'; 
    browser 
     .url(siteroot) 
     .waitForElementVisible('body', 1000) 
     .setValue('input[id=UserNameEdit]', user) 
     .setValue('input[id=PasswordEdit]', pass) 
     .click('#LoginBtn') 
     .pause(1000) 
     .assert.containsText('#usergreeting', greeting) 
    } 
}; 
+1

您將其定義爲module.exports的屬性,它不在可變範圍內。 – 2015-03-30 18:21:04

+0

簡化示例:'var foo = {bar:42,baz:function(){}};'。 'bar'不會在'foo.baz'裏面變成一個變量。這就是JS的工作原理,與Node無關。 – 2015-03-30 18:22:51

+0

你是對的:我誤解了代碼。謝謝。 – stackleit 2015-03-31 20:34:01

回答

1

這不是範圍問題。

config不是一個變量。它是對象的屬性(或者一旦對象文字完成了評估)。您需要訪問this.config

+0

謝謝:我徹底吹過了明顯的。對不起,謝謝澄清。 – stackleit 2015-03-31 20:35:02