0
<script>
this.document = "xxxx";  // why it doesn't make sense?
console.log(document);   // still show document obj in devtools
</script>

I think maybe this be banned by javascript engine.

4

3 回答 3

1

window.document is not a writeable property. If you want a local variable named document you can do so:

(function(){
  var document = 'xxxx';
  console.log(document);
})();

and:

new function(){
  this.document = 'xxxx';
  console.log(this.document);
};

Both will log 'xxxx'

于 2013-08-30T01:52:19.013 回答
1

Sometimes it makes sense - and is allowed, for example you can reassign intristic function window.alert.

But in 99% cases you better leave it well enough alone.

于 2013-08-30T01:54:01.467 回答
1

Re-assigning built ins yields non-portable behavior.

Library A relies heavily on document.getElementById. Library B relies on its own custom version, but replaced the getElementById on the document prototype with its own custom version. Library A breaks.

Therefore, library A, which is designed to work with and is tested against all browsers, won't work.

It's the same argument as global variables. Built-ins are basically global variables.

于 2013-08-30T02:12:19.113 回答