<html>
<head>
</head>
<body onload=>
<button></button>
<script>
function give_show(value) {
return function() {
console.log(value);
}
}
var button_element =document.getElementsByTagName('button')[0];
button_element.addEventListener('load',give_show('bong!'),false)
</script>
</body>
</html>
以上代码有效。在控制台我得到了:
bong!
但是,如果我更改此部分:
function give_show(value) {
return function() {
console.log(value);
}
到
function give_show(value) {
return function(value) {
console.log(value);
}
我有点像
mouse.event
导致这种情况发生的原因是什么?
仅供参考:我使用Safari控制台来获得结果。
答案 0 :(得分:2)
嵌套函数可以访问创建它们的作用域中定义的所有内容。所以:
function give_show(value){
return function(){ console.log(value); }
}
当你在嵌套函数中引用value
时,give_show
中定义的变量在范围内并被使用。
但是,当你这样做时:
function give_show(value){
return function(value){ console.log(value); }
}
您将返回一个带参数value
的函数,以便变量名隐藏give_show
定义的名称。
为了使第二种情况下发生的事情变得更加明显,这段代码完全相同,不会将value
变量隐藏在外部范围内:
function give_show(value){
return function(event){ console.log(event); }
}
console.log
方法正在使用传递给返回函数的参数,并且完全忽略传递给give_show
的值。这就是为什么你得到'mouse.event'而不是'bong!'在第二种情况下 - 事件处理程序作为参数传递给事件。
答案 1 :(得分:1)
这是因为在您调用console.log(value);
时,value
变量指的是最内部函数的参数。此参数会覆盖您传递到give_show
的参数的值,因为它具有相同的名称。当单击事件调用该函数时,浏览器会将实际的click事件对象作为第一个参数传递给该内部函数,这就是您mouse.event
执行console.log
时的原因。
答案 2 :(得分:1)
你可以这样形象化......
function give_show(value) { // <-- 1. You passed 'bong!'
return function(value) { // <-- 2. Browser passes the Event object <--------+
// |
console.log(value); // <-- 3. Will use the nearest "value" it finds ----+
};
}
因此返回的函数用作事件处理程序。当事件发生时,浏览器将Event
对象传递给该函数。由于您将参数命名为value
,console.log
将使用该参数。
如果您没有将名称value
提供给处理程序函数,则下一个value
将是give_show
函数中定义的{...}}。
function give_show(value) { // <-- 1. You passed 'bong!' <----------------------+
// |
return function(foo) { // <-- 2. Browser passes the Event object |
// |
console.log(value); // <-- 3. Will use the nearest "value" it finds ----+
};
}
答案 3 :(得分:0)
我在列表人员上更改load
click
并在返回内部函数之前添加console.log
:
<html>
<head>
</head>
<body>
<button></button>
<script>
function give_show(value) {
console.log(value);
return function(value) {
console.log(value);
}
}
var button_element =document.getElementsByTagName('button')[0];
button_element.addEventListener('click',give_show("bong!"),false);
</script>
</body>
</html>
混淆是give_show
传递给addEventListner
的时候。在示例give_show
之前运行,然后单击按钮并在控制台上写入Bong!
。 addEventListner
仅识别功能:
function(value) {
console.log(value);
}
和事件(点击)传递给value
鼠标点击的位置。这是相同的:
button_element.addEventListener('click',function(value) {
console.log(value);
},
false);
如果您取消value
参数value
,则传递给give_show
函数。