开发者

Trying to simplify some Javascript with closures

开发者 https://www.devze.com 2022-12-31 10:20 出处:网络
I\'m trying to simplify some JS code that uses closures but I am getting nowhere (probably because I\'m not grokking closures)

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 t开发者_运维技巧his 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


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()...?)

0

精彩评论

暂无评论...
验证码 换一张
取 消