更新时间:2022-05-03 08:24:48
您的代码适用于我,但您可能想解决 x
使用 window.x
显式地显示全局变量。
当不在浏览器环境中,或者全局对象不在的环境中时t叫窗口
,试试:
Your code works fine for me, but you might want to resolve x
to the global variable explicitly by using window.x
.
When not in a browser environment, or an environment where the global object isn't called window
, try:
(window || root || global || GLOBAL || this || self || {x: undefined).x
{x:undefined}
object literal只是为了确保表达式不会引发错误。
我列出的所有名字都是我所知道的给予(严格说来说是无名的)全局对象,只需使用可能适用于你的情况的对象。
The {x:undefined}
object literal is just to make sure the expression doesn't throw up errors.
I've listed pretty much all names I know of that are given to the (strictly speaking nameless) global object, just use the ones that might apply to your case.
另一方面,如果全局变量 a )时,可以重新分配c> x ,闭包更可取:
On the other hand, if the global variable x
might be reassigned by the time the function (a
) gets called, a closure would be preferable:
a = (function (globalX)
{
return function a(param)
{
console.log(globalX);
return oldA(param);
};
}(x || window.x));//pass reference to x, or window.x if x is undefined to the scope
当然,如果你处于严格模式,你也需要小心隐含的全局变量。
我能想到的就是你的代码出了问题,一些更多的细节可能会为我们提供实际发生的事情的线索......
Of course, if you're in strict mode, you need to be careful with implied globals, too.
That's all I can think of that is going wrong with your code, some more details might provide us with a clue of what's actually happening...