sourcecode

JavaScript에서 창, 화면, 문서의 차이점은 무엇입니까?

copyscript 2022. 9. 25. 00:16
반응형

JavaScript에서 창, 화면, 문서의 차이점은 무엇입니까?

이러한 용어는 DOM의 글로벌 환경으로서 서로 교환할 수 있습니다.어떤 차이점(있는 경우)과 어떤 경우에 각각 사용해야 합니까?

Window는 메인 JavaScript 오브젝트 루트입니다.global object문서 오브젝트 모델의 루트로 취급할 수도 있습니다.액세스 할 수 있습니다.window.

window.screen아니면 그냥screen는 물리적인 화면 치수에 관한 작은 정보 객체입니다.

window.document아니면 그냥document는 잠재적으로 표시되는(또는 렌더링된) 문서 객체 모델/DOM의 주요 객체입니다.

부터window는 글로벌 오브젝트입니다.속성 이름만으로 그 속성을 참조할 수 있기 때문에 적어 둘 필요가 없습니다.window.- 런타임으로 알 수 있습니다.

브라우저에 가장 먼저 로드되는 것은 창입니다.이 창 개체는 길이, innerWidth, inner와 같은 속성의 대부분을 가집니다.높이, 이름, 닫힌 경우 부모 등입니다.

그러면 문서 오브젝트는 어떻게 됩니까?문서 오브젝트는 브라우저에 로드되는 html, aspx, php 또는 기타 문서입니다.문서는 실제로 창 오브젝트 안에 로드되며 제목, URL, 쿠키 등과 같은 속성을 사용할 수 있습니다.이게 무슨 뜻일까요?즉, 창의 속성에 액세스하려면 window.property, document인 경우 window.document.property로 요약하면 document.property로 사용할 수 있습니다.

dom

그것은 충분히 간단해 보인다.하지만 IFRAME이 도입되면 어떻게 될까요?

iframe

간단히, 아래에 더 자세히 설명하겠습니다.

  • window는 해당 컨텍스트의 JavaScript 실행 컨텍스트 및 글로벌 객체입니다.
  • documentHTML 해석에 의해 초기화된DOM 이 포함되어 있습니다.
  • screen에 물리 디스플레이의 전체 화면을 나타냅니다.

이러한 개체에 대한 자세한 내용은 W3C Mozilla 참조를 참조하십시오.이 세 가지 중 가장 기본적인 관계는 각 브라우저 탭이 고유하다는 것입니다.window, 및 awindow가지다window.document그리고.window.screen특성.브라우저 탭의window글로벌 콘텍스트이기 때문에document그리고.screen언급하다window.document그리고.window.screen3개의 오브젝트에 대한 자세한 내용은 Flanagan의 JavaScript에 따라 다음과 같습니다. 최종 가이드

window

각 브라우저 탭에는 자체 최상위 수준이 있습니다.window물건.각각<iframe>(더 이상 사용되지 않음)<frame>) 요소에 독자적인 요소가 있습니다.window상위 창 내에 중첩된 개체도 있습니다.각 창에는 고유한 글로벌 개체가 있습니다. window.window항상 을 참조하다window,그렇지만window.parent그리고.window.top는 다른 실행 콘텍스트에 대한 접근을 허용하는 창을 포함하는 것을 나타낼 수 있습니다.에 더하여document그리고.screen다음에 설명하겠습니다.window속성에는 다음이 포함됩니다.

  • setTimeout()그리고.setInterval()이벤트 핸들러의 타이머로의 바인딩
  • location현재 URL 제공
  • history방법을 써서back()그리고.forward()탭의 가변 기록 제공
  • navigator브라우저 소프트웨어 설명

document

각각window오브젝트에는 다음이 있습니다.document렌더링할 오브젝트.이러한 오브젝트는 일의의 ID를 할당할 때 HTML 요소가 글로벌오브젝트에 추가되기 때문에 부분적으로 혼동됩니다.예: HTML 스니펫에서

<body>
  <p id="holyCow"> This is the first paragraph.</p>
</body>

문단 요소는 다음 중 하나에 의해 참조될 수 있습니다.

  • window.holyCow또는window["holyCow"]
  • document.getElementById("holyCow")
  • document.querySelector("#holyCow")
  • document.body.firstChild
  • document.body.children[0]

screen

window오브젝트에는screen물리적 디스플레이를 설명하는 속성을 가진 개체:

  • 화면 속성width그리고.height전체 화면입니다.

  • 화면 속성availWidth그리고.availHeight툴바를 생략하다

렌더링된 문서를 표시하는 화면의 부분은 JavaScript의 뷰포트입니다.운영체제와의 상호작용에 대해 이야기할 때 화면의 애플리케이션 부분을 창이라고 부르기 때문에 혼란스러울 수 있습니다.getBoundingClientRect()임의의 방법document요소가 개체를 반환합니다.top,left,bottom,그리고.right뷰포트에서 요소의 위치를 설명하는 속성.

window는 실제 글로벌오브젝트입니다

screen는 화면이며, 사용자의 디스플레이에 대한 속성이 포함되어 있습니다.

documentDOM이 있는 곳입니다.

window모든 것이 포함되어 있기 때문에,window.screen그리고.window.document그런 요소들을 얻기 위해서요이 바이올린을 체크해 주세요.각 오브젝트의 컨텐츠는, http://jsfiddle.net/JKirchartz/82rZu/ 에서 확인할 수식되고 있습니다.

Firebug/development 툴에서도 다음과 같은 오브젝트의 내용을 확인할 수 있습니다.

console.dir(window);
console.dir(document);
console.dir(screen);

window모든 것의 근원이라는 것을,screen화면 치수만 있고document상위 DOM 객체입니다.그래서 이렇게 생각하면 돼요.window슈퍼맨 같은...document...

콘솔에서 쓰기

this

또는

window

Enter 키를 누르면 브라우저의 최상위 개체인 에 액세스할 수 있습니다.또한 다음 중 하나의 속성을 사용하여 액세스할 수도 있습니다.

top

parent

self

globalThis

even combined in between.

Indeed, checking any pair of those above will return true :

this === window // true

window === globalThis // true

this === self // true

parent === window // true

top === parent // true

even some multiple combinations of them -- fact possible for the reason that

window.window === window // true

because window is also its own property, so we can even write window.window.window === window as well, or even stuff like window.window.self.top.parent.globalThis === window, all those returning true.

The only exception is that we can't use this on the last position because it isn't a property (therefore window.window.this === window // false because actually window.this === undefined // true, as window has NOT a such this property).

As a result, we can't write self.this , top.this , parent.this , window.this , the only way possible being to replace it instead with globalThis in the last position, as a property of window, like in top.globalThis etc.


When having a webpage with frames, each frame document would belong to an own separate window object, that separate window being a child of the previous top level window shown earlier - you can simply test that on a platform with frames (like jsfiddle, codepen, w3schools) where writing and executing in the frame console.log(window.parent === window); will return false while if you write window.parent === window directly in console will return true. In the frame, window.parent will access the global window (the parent of frame window object being obviously not the same as the frame window object itself). You can check content of each these windowS separately running in the frame the codes (and seeing results like):

console.log(window.document.all); // HTMLAllCollection(6) [html, head, body, p#demo, button, script, demo: p#demo]

respectively

console.log(window.parent.document.all); // HTMLAllCollection(335) [html, head, script, script, title, meta, meta, meta, meta, meta, meta, meta, meta, link, link, link, link, script, script, script, script, script, script, script, script, script, style, script, script, script, script, style, script, meta, meta, meta, meta, meta, meta, meta, meta, script, argprec0, argprec1, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, …] - therefore much more elements contained in the parent document

Doing same check, but from the console this time:

window.document.all // HTMLAllCollection(335) [html, head, script, script, title, meta, meta, meta, meta, meta, meta, meta, meta, link, link, link, link, script, script, script, script, script, script, script, script, script, style, script, script, script, script, style, script, meta, meta, meta, meta, meta, meta, meta, meta, script, argprec0, argprec1, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, link, script, …] - again the same huge elements list

As we see, the console (open it with F12) has access to the most top level window scope / context (versus the frame underneath that is contained in its own limited context / scope) so it shows all elements at once. This is same context we started to refer in the beginning as well.


Going further with the main concepts, there is even more to understand. In saying that window is the top level object in browser one should understand that it is a certain representation in the memory of the browser (software called client) from where the browser will paint (render) the visible page (which we refer to as a document - again, accesible as a property of window).

As such, we can access the document in console - to see its structure - simply using window.document where we can see everything in it by clicking on #document. Again, we will see there a representation of the document, not the document itself. That representation seen in console is the DOM, being a Model of the original file, and is created by taking PLUS improving in a certain way, where needed, the data parsed from source code of the original document by the JavaScript engine of the browser. The source code is immutable (the browser doesn't change the html file received from internet), while the DOM is mutable (and the mutations are made by JavaScript code ran into the browser either before or after the page is rendered on the device hardware). For clarity: what we see in console is DOM, what we see in browser is the rendering and what we see in source code is the original file. They're not the same, everyone is different from the other two.

To help you understand, I would compare that process with client software being in "real life" some talented person visiting the Louvre museum and seeing the Monalisa painting (the source code file). The image of Monalisa in tourist mind isn't the same as the original painting made by Leonardo, it's just a mental representation of it. From it, the talented tourist will then recreate again on his brain some "own" Monalisa, improving here and there what should be improved or changed before finally painting when back at home on a canvas all the colors of the original image plus even more.

Therefore, we have 3 'entities' (a- html file, immutable, containing the source code, b- one representation of it, created after the source code is parsed and "understood" by the browser or improved, c- the rendering itself that is displayed on the screen). The primary improvement mentioned can be like adding closing tags where missing previously in the source file, adding or deleting elements inside the Model, according to the script instructions contained in the source file, changing them, requesting further resources (as images, fonts, css files, media files to be used as assets of the final full page, etc) and so on.

Despite of similarity in names, a window related to a specific document and browser window shouldn't be considered as the same thing, the first one being attached to the later one (and accesible as a property of it). Likewise, when having multiple browser windows (say 10 instances), each one with multiple tabs (or not), those are attached to the browser window, and their objects accesible by window[0] up to window[9].

Regarding the screen, browser client is a software (a code) that runs and executes another software (source code) for the purpose of finally displaying that (second) code on the hardware device (monitor / screen) through several layers. For this purpose, browser software has also actually its own separate programming routines able to interact with the operating system in order to detect the screen resolution, size, color depths, some settings and more, therefore it acts as a bridge between the operating system and the files meant to be displayed on its rendering area.

Using console.log(window.screen) will return to us the details collected from the OS by the browser about the device monitor (and stored in its memory) such as {availWidth: 1920, availHeight: 1040, width: 1920, height: 1080, colorDepth: 24, …}

A simpler code can be used (no need to write always the window word) and extract for example the width of the device:

console.log(screen.width) // 1920

You can use such data even for executing some pseudo media queries based purely on JavaScript and with no CSS whatsoever - for example

function goMobile() {
    if (screen.width < 900) {location.replace("/index-mobile.html");}
}
goMobile();

As a conclusion: window and document belong to DOM, screen doesn't. You need all of them, however because document and screen are both properties of window object, you can just invoke them directly in your code (shortening the code). More, screen being about the hardware part, not any browsers' rectangular available area to render on, it hasn't the meaning of document.body. At most, you can put screen data to use in order to optimize your loading page, for example limiting the assets downloads for a better mobile device experience and so on.

The window object is simply like the root of them all to which document and screen are properties of. The screen is just the user display area, document is the DOM containing all html elements, their classes and attributes. So, the window is the parent object while they are children objects. https://developer.mozilla.org/en-US/docs/Web/API/Window https://developer.mozilla.org/en-US/docs/Web/API/Window/screen

ReferenceURL : https://stackoverflow.com/questions/9895202/what-is-the-difference-between-window-screen-and-document-in-javascript

반응형