[英]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.