Javascript 函数名中包含无效字符
我试图滥用Chrome开发工具中的函数名:Javascript 函数名中包含无效字符,javascript,function,global,window-object,Javascript,Function,Global,Window Object,我试图滥用Chrome开发工具中的函数名: window["hello world"] = function () { console.log("Hello World!"); } 上面的行将创建hello worldglobal函数 它也出现在自动完成建议中: 如果我们这样称呼它(hello world()),我们会得到一个语法错误,应该是这样的: SyntaxError: Unexpected identifier 但是,如果不使用引号(window[“hello world”]())
window["hello world"] = function () { console.log("Hello World!"); }
上面的行将创建hello world
global函数
它也出现在自动完成建议中:
如果我们这样称呼它(hello world()
),我们会得到一个语法错误,应该是这样的:
SyntaxError: Unexpected identifier
但是,如果不使用引号(
window[“hello world”]()
),我们如何调用此函数?您根本没有给函数命名。它是一个匿名函数,分配给窗口
对象的属性
由于属性名称中有空格,因此不能使用标识符访问它,因此访问它的唯一方法是显式使用窗口对象
window["hello world"]();
如果您真的想在不使用引号的情况下运行函数,那么可以执行以下操作。请注意,这是一种反常的黑客行为,而不是您应该在生产代码中执行的操作
window["hello world"] = function () { console.log("Hello World!"); }
// No quotes for any of the code used to access the above.
window[
[ 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100 ].map(
function (currentValue) {
return String.fromCharCode(currentValue);
}
).join(new String)
]();
好主意。:-)请注意,这是一种反常的黑客行为,而不是您应该在生产代码中执行的操作。-当然,一切或多或少都是一个笑话,只是为了发现这些财产名称的局限性。