JavaScript:与其他变量同名的回调函数参数? [英] JavaScript: callback function parameter with same name as other variable?

查看:39
本文介绍了JavaScript:与其他变量同名的回调函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var str = 'internet';

performAction(function(str) {
    console.log(str);
});

拥有私有变量 str 并且还有一个带有同名参数的回调函数有问题吗?

Is there a problem with having a private variable str and also having a callback function with a parameter of the same name?

谢谢!

推荐答案

这只是一个标准的作用域情况——它是作为参数传递给另一个函数的匿名函数表达式这一事实并不重要.请注意,在您的 performAction() 函数(您没有显示)中,它将无法访问作为回调函数参数的 str - 如果 performAction() 引用 str 它将获得全局internet"变量(或它自己的本地 str 如果已定义).

This is just a standard scope situation - the fact that it is an anonymous function expression passed as a parameter to another function doesn't matter. Note that within your performAction() function (which you don't show) it will not have any access to the str that is the parameter of the callback function - if performAction() references str it will get the global "internet" variable (or its own local str if defined).

就作用域而言,函数的参数与该函数的局部变量相同,这意味着它们从外部作用域屏蔽了同名的其他变量 - 但即使定义在更广泛的作用域中,仍可以访问具有不同名称的变量.

A function's parameters are, for scope purposes, the same as that function's local variables, which means they mask other variables of the same name from outer scope - but variables with different names can still be accessed even if defined in a wider scope.

如果你做这样的事情,可能会让人困惑的地方:

Where it could get confusing is if you do something like this:

var str = "internet";

(function(str) {
  console.log(str); // "internet"
  str = "local param";
  console.log(str); // "local param"
})(str);

console.log(str); // "internet"

在那种情况下,我有一个函数,它带有一个名为 str 的参数,但是当我调用它时,我传入了一个不同的 str.请注意,在该函数中更改 str 只会更改本地 str,而不是全局的.它们是两个不同的变量...

In that case I have a function with a parameter called str but when I call it I'm passing in a different str. Note that changing str within that function only changes the local str, not the global one. They are two different variables...

这篇关于JavaScript:与其他变量同名的回调函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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