Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

javascript - window.location versus just location

Across the web, I see a vast number of JavaScript programmers writing window.location instead of just location. I was curious if anyone could offer an explanation as to why. window is the global object, and therefore it is unnecessary to include -- isn't it? I mean, you don't see people write window.Math.floor or new window.Date(), so I'm curious as to why it would be specified with location.

I understand that location is considered to be a "property" of the window you're in, which I suppose makes some sense. But even so, I don't see any reason to specify the global object; it's not possible to overwrite location in the first place, not without redirecting the page.

So, is this just a quirk that has been used for so long that it's become integrated with how we write JavaScript, or is there some tangible reason to do things this way? I checked Google, but alas, I came up with nothing...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I always use window.location in my code for two principal reasons:

  1. It's a good habit to avoid global variables whenever possible. Using the window. prefix reminds me that the variable is global and that others aren't.
  2. The nature of Javascript's scoping allows you to override variables set higher up the scope tree. This means that you could have set var location somewhere in a containing scope (it's not an unlikely word to use as a variable name) and you'd be working on that instead.

For me, clarity of purpose when coding is very important as it helps me avoid writing bugs and then helps me find them when I do.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...