Trying to simplify some Javascript with closures

I am trying to simplify some JS code that uses a closure, but I can't get anywhere (maybe because I don't close the closure)

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 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, it doesn't seem to work ... Thus: - What am I doing wrong? - Is it possible to do this? - as?

TIA

- MV

-1


a source to share


1 answer


Without configuring the object properly, you are putting the function names as strings in 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 how you define methods inside the object, but you're not sure what you have there (http.createServer () ...?)

0


a source







All Articles