尝试简化一些Javascript与闭包 [英] Trying to simplify some Javascript with closures

查看:127
本文介绍了尝试简化一些Javascript与闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图简化一些使用闭包的JS代码,但我无处可能(可能是因为我不是grokking闭包)



我有一些代码看起来像这样:

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

我试图以这种方式简化:

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

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

function alertPUT(){
alert('PUT');不幸的是,似乎没有工作...
因此:
}


$ b b $ b - 我做错了什么?
- 有可能做到这一点吗?
- 如何?



TIA



- MV


< div类型=h2_lin>解决方案

没有正确设置对象,你把函数名称作为字符串在httpmethods对象中,而不是给它们名称 - 尝试这样: p>

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


b $ b

这是你在对象中定义方法的方法,但不知道你在那里的其他东西(http.createServer()...?)


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

解决方案

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

这篇关于尝试简化一些Javascript与闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆