简体   繁体   English

将函数分配给“名称”变量时,为什么我的代码不起作用?

[英]Why my code does not work when I assign a function to “name” variable?

I am testing this code but something weird happening. 我正在测试此代码,但发生了一些奇怪的事情。 It shows an error 显示错误

Uncaught Typeerror: name is not a function 未捕获的Typeerror:名称不是函数

but if I change "name" to anything else, it works ! 但是,如果我将“名称”更改为其他名称 ,它将起作用!

( name = function (x) {console.log(x || "not set");})();
name ('Rami');

This is the error appearing on Chrome Console 这是Chrome控制台上出现的错误

错误截图

The reason is that in a browser context, "name" refers to "window.name" implicitly. 原因是在浏览器上下文中,“名称”隐式指代“ window.name”。

Are you aware that the function gets called twice? 您是否知道该函数被调用两次?

If you just want to return a function pointer, you could use this: 如果只想返回一个函数指针,则可以使用以下命令:

name2 = function (x) {console.log(x || "not set");};
name2('Rami');

You're calling the function from outside of the IIFE 's scope 您是在IIFE范围之外调用函数

This would be the correct way to do so: 这将是正确的方法:

(function() {
  const name = function(name) {
    console.log('Hello ' + name);
  }
  name('Rami');
}());

Example: https://repl.it/MX9O 示例: https//repl.it/MX9O

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Axios - 动态标题不起作用。 为什么我的代码在动态设置变量时不起作用,但在硬编码时却起作用? - Axios - Dynamic Header not working. Why does my code not work when i set the variable dynamically but does when i hard code it? 为什么在我的 JS 文件中编写 JS 代码时,我的 JS onscroll 功能不起作用? - Why does my JS onscroll function dont work when I write the JS code in my JS file? 当我在for循环中复制变量时,为什么我的JavaScript代码有效 - Why does my JavaScript code work when I copy a variable in a for loop 为什么我的 addEventListener function 为变量在本地而不是全局赋值? - Why does my addEventListener function assign a value to a variable locally, but not globally? 为什么我的函数在调用时不起作用? - Why does my function not work when called? 为什么在分配变量时控制台打印未定义? - Why does the console print undefined when I assign a variable? 将变量赋值给函数在JavaScript中不起作用? - Assign variable to function does not work in JavaScript? 为什么我的代码只能在html中工作,而在将其放入Javascript页面时却不能工作? - Why does my code only works in html but does not work when I put it into a Javascript page? 除非我在另一个变量中引用了deffered()函数,否则为什么我的deffered()函数不起作用? - Why does my deffered() function not work unless I reference it thourgh another variable? 为什么我在 React 中的简单名称更改 function 不起作用? - Why does my simple name change function in React not work?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM