Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
试图用闭包简化一些Javascript_Javascript_Closures - Fatal编程技术网

试图用闭包简化一些Javascript

试图用闭包简化一些Javascript,javascript,closures,Javascript,Closures,我试图简化一些使用闭包的JS代码,但我一事无成(可能是因为我没有摸索闭包) 我有一些代码如下所示: var server = http.createServer(function (request, response) { var httpmethods = { "GET": function() { alert('GET') }, "PUT": function() { alert(

我试图简化一些使用闭包的JS代码,但我一事无成(可能是因为我没有摸索闭包)

我有一些代码如下所示:

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() { 
      alertGET()
    },
    put: function() {
      alertPUT()
    }
};

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

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

httpmethods.get()
httpmethods.put()
我试着用这种方式来简化它:

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

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

function alertPUT() {
    alert('PUT');
} 
不幸的是,这似乎不起作用。。。 因此: -我做错了什么? -有可能这样做吗? -怎么做

短暂性脑缺血发作


--MV

如果未正确设置对象,则将函数名作为字符串放入httpmethods对象中,而不是给它们命名-请尝试以下操作:

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() { 
      alertGET()
    },
    put: function() {
      alertPUT()
    }
};

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

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

httpmethods.get()
httpmethods.put()

这是定义对象内部方法的方式,但不确定对象中的其他内容(http.createServer()…?)

似乎不起作用
不是一个非常精确的问题描述。如果您得到一个
警报,则该警报是未定义的
类错误,您应该尝试将函数声明放在
服务器
函数之前。除此之外,这似乎是完全合法的。是什么让你觉得将匿名函数移到外部是在简化事情呢?你的代码应该可以工作,你需要提到什么不工作(什么是预期的行为)以及你收到的是什么样的错误消息。我不知道http.createServer()方法中有什么。。在没有看到全部代码的情况下,这有点棘手,但基本问题是如何在httpmethods对象上定义.get()和.put()函数。去掉引号就可以了。引号没有问题——它们是完全合法的。这个例子完美地演示了对象文字的属性,但没有演示闭包。