[removed] versus just location

2019-01-11 00:32发布

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...

9条回答
爷、活的狠高调
2楼-- · 2019-01-11 00:55

It's just a matter of style.

Conceptually, location is a property of the window (the window is at a location), unlike Math or Date.

查看更多
【Aperson】
3楼-- · 2019-01-11 00:57

Part of coding is clarity. Unlike Math or Date, location is conceptually a property of the window, so the code becomes more clear to include it. The "window." prefix should ideally be removed for minification.

You are probably correct that a lot of the reason is historical. Javascript has an extensive history of copying and pasting.

查看更多
爷、活的狠高调
4楼-- · 2019-01-11 00:59

The window object is the default working namespace, so location will be equal to window.location.

I think that using location is a bit ambiguous, use window.location for clarity.

查看更多
登录 后发表回答