English 中文(简体)
如果window.undefine被覆盖,则获取未定义
原标题:Get undefined if window.undefined is overwritten

看起来<code>window.undefined</code>是可写的,也就是说,它可以设置为默认值以外的其他值(不出所料,<code>undefined

然而,问题是,每当我提到<code>undefined</code>时,它都指的是<code>窗口。undefined

那么,我实际上是如何访问一个<code>未定义的

如果我编码:

window.undefined =  foo ; // This code might have been executed by someone/something
var blah = undefined; // blah is not undefined, but equals to  foo  instead...

我怎么可能解决这个问题?

最佳回答

这个问题的“标准”解决方案是使用内置的void运算符。其唯一目的是返回未定义的:

var my_undefined = void 0;

除此之外,还有其他方法可以获得<code>未定义的

如果您不<code>返回</code>任何内容,那么函数将返回未定义的值,因此您可以执行以下操作

this_is_undefined = (function(){}());

如果没有向函数传递足够的参数,也会导致未定义。所以一个常见的习语是

function foo(arg1, arg2, undefined){ //undefined is the last argument
    //Use `undefined` here without worrying.
    //It is a local variable so no one else can overwrite it
}
foo(arg1, arg2);
//since you didn t pass the 3rd argument,
//the local variable `undefined` in foo is set to the real `undefined`.

这种方法特别适用于同时定义和调用函数的情况,这样就不会有忘记和传递错误数量的参数的风险。

问题回答

除了其他解决方案外,您还可以执行void 0技巧,该技巧始终返回未定义的,而与窗口属性无关。

window.undefined =  foo ;
var blah = void 0;

alert( blah );  // undefined

实际上,将任何东西与<code>undefined</code>进行比较都不是一个好主意。应使用类型的运算符:

function isUndefined ( variant ) { return typeof variant ===  undefined  }

只声明一个变量而不将其赋值给任何东西就足够了:

var local_undefined;
alert(typeof local_undefined);

但是,究竟为什么可以更改未定义的值呢?有人知道这背后的历史吗?





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签