Trying to simplify some Javascript with closures

早过忘川 提交于 2019-12-12 07:06:11

问题


I'm trying to simplify some JS code that uses closures but I am getting nowhere (probably because I'm not grokking closures)

I have some code that looks like this:

var server = http.createServer(function (request, response) {
    var httpmethods = {    
        "GET": function() {
            alert('GET')
        },
        "PUT": function() {
            alert('PUT')
        }
    };
});

And I'm trying to simplify it in this way:

var server = http.createServer(function (request, response) {
    var httpmethods = {    
        "GET": function() {
            alertGET()
        },
        "PUT": function() {
            alertPUT()
        }
    };
});

function alertGET() {
    alert('GET');
}

function alertPUT() {
    alert('PUT');
} 

Unfortunately that doesnt seem to work... Thus: - what am I doing wrong? - is it possible to do this? - how?

TIA

-- MV


回答1:


Not setting up the object properly, you're putting the function names as strings inside the httpmethods object, instead of giving them names - try something like this:

var server = http.createServer( function (request, response) {});

var httpmethods = {
    get: function() { 
      alertGET()
    },
    put: function() {
      alertPUT()
    }
};

function alertGET() {
        alert('GET called');
}

function alertPUT() {
        alert('PUT called');
}

httpmethods.get()
httpmethods.put()

This is the way you define the methods inside the object, but not sure about the other stuff you have there (http.createServer()...?)



来源:https://stackoverflow.com/questions/2840655/trying-to-simplify-some-javascript-with-closures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!