簡體   English   中英

為什么在node.js中得到這個奇怪的“無法設置未定義的屬性”

[英]Why am I getting this weird “Cannot set property of undefined” in node.js

我有一個非常簡單的nodeunit測試,就像這樣:

'use strict';

var controllerUtils = require('../lib/controllerUtils');

function Mock() {
    this.req = { headers: {} };
    this.res = { };
    this.nextWasCalled = false;
    this.next = function() {
        this.nextWasCalled = true;
    };
}

module.exports = {
    'acceptJson': {
        'Verify proper headers were set': function(test) {
            var mock = new Mock();
            controllerUtils.acceptJson(mock.req, mock.res, mock.next);

            test.ok(mock.nextWasCalled);
            test.equal(mock.req.headers.accept, 'application/json');
            test.equal(mock.res.lean, true);
            test.done();
        }
    }
}

但是,當我調用controllerUtils.acceptJson時,出現錯誤TypeError: Cannot set property 'nextWasCalled' of undefined

所以我已經在chrome的控制台和節點命令行上對其進行了測試,測試是:

function Mock() {
    this.req = { headers: {} };
    this.res = { };
    this.nextWasCalled = false;
    this.next = function() {
        this.nextWasCalled = true;
    };
}

var m = new Mock();
console.log(m.nextWasCalled); //logs false
m.next();
console.log(m.nextWasCalled); //logs true

我無法弄清楚為什么我的代碼無法正常工作,因為這是一個非常瑣碎的代碼,並且在chrome的控制台和節點命令行上都可以正常工作。

PS .: controllerUtils.acceptJson代碼:

module.exports.acceptJson = function(req, res, next) {
    req.headers.accept = 'application/json';
    res.lean = true;

    next();
};

controllerUtils.acceptJson獲取對函數的引用作為參數。 它不知道應該在哪個上下文中調用該函數,因此它在沒有任何上下文的情況下調用它。

next方法要求上下文是定義它的對象。 有兩種方法可以修復您的代碼:

將函數作為參數傳遞時,將函數綁定到上下文:

controllerUtils.acceptJson(mock.req, mock.res, mock.next.bind(mock));

定義函數時將其綁定到上下文:

this.next = function() {
    this.nextWasCalled = true;
}.bind(this);

暫無
暫無

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

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