BOM

The BOM(Browser Object Model) is really the heart of JS, it provides a lot of objects for accessing browser functionality.

1. Window object
  • The core object of the BOM is the Window, which represents an instance of the browser. The Window object has the dual role of being both an interface to access the browser window through JS and a Global object as specified in ECMAScript. This means that any object, variable, and function defined in a web page has the Window as its Global object.

All variables and functions declared in the global scope become properties and methods of the window object.

var age = 18
function sayAge () {
  console.log(this.age) // 18
}
console.log(window.age) // 18
sayAge()
console.log(window.sayAge()) // 18
Copy the code

We define the age variable and the function sayAge() in the global scope, which are automatically assigned to the window object. Thus, the variable age can be accessed through window.age and the function sayAge() can be accessed through window.sayage (). Since sayAge() exists in the global scope, this.age is mapped to window.age.

  • JS is a single-threaded language that allows code to be scheduled to execute at a specific time by setting timeout values and intermittent time values. The former is executed after a specified time, while the latter is executed at specified intervals

Timeout calls require the setTimeout() method of the window object

setTimeout(function, milliseconds, param1, param2, ...) Function: required. To call a code string, it can also be a function. Milliseconds: optional. The amount of time to wait, in milliseconds, to execute or call code/function. The default is 0. param1, param2, ... : optional. Additional arguments passed to the executing function (not supported by IE9 and earlier versions)Copy the code
SetTimeout (function () {console.log('Hello World')}, 1000) setTimeout(function () {console.log('Hello World')}, 1000) setTimeout(function () {console.log('Hello World')}, 1000) Is a number of milliseconds that indicates how long to wait, but after that time the specified code may not executeCopy the code

JS is a single-threaded parser, so only one piece of code can be executed at a time. In order to control the code to be executed, there is a JS task queue. The tasks are executed in the order they were added to the queue. The second parameter of setTimeout() tells JS how long it will take to add the current task queue to the queue. If the queue is empty, the added code will execute immediately. If the queue is not empty, it waits until the previous code has finished executing

After calling setTimeout(), the method returns a numeric ID representing the timeout call. The timeout call ID is a unique identifier for the code scheduled to execute and can be used to cancel the timeout call. To cancel timeout calls that have not yet been executed, you can call the clearTimeout() method and pass it the corresponding timeout call ID as an argument

let timeoutId = setTimeout(function () {
    console.log('Hello world')
  }, 1000)
  clearTimeout(timeoutId)
Copy the code

Immediately after setting the timeout call, the code calls clearTimeout() as if nothing had happened.

An intermittent call is similar to a timeout call, except that it repeats the code at a specified interval until the intermittent call is canceled or the page is unloaded. To set intermittent calls, setInterval() takes the same argument as setTimeout()

Calling the setInterval() method also returns an intermittent call ID that can be used to cancel an intermittent call at some point in the future. To cancel an intermittent call that has not yet been executed, use the clearInterval() method and pass in the corresponding intermittent call ID.

Var num = 0 var Max = 10 var intervalId = null function increatNumber () {num++ // If (num == Max) {clearInterval(intervalId) console.log('done')}} intervalId = setInterval(increatNumber, 500).Copy the code

In this example, the variable num is incremented every half second, and the previously set intermittent calls are cancelled when incremented to the maximum. This pattern can also be implemented using timeout calls

var num = 0
var max = 10
function increatNumber () {
  num++
  if (num < max) {
    setTimeout(increatNumber, 500)
  } else {
    console.log('done')
  }
}
setTimeout(increatNumber, 500)
Copy the code

As you can see, there is no need to keep track of the timeout call ID when using a timeout call, because after each code execution, if another timeout call is not set, the call will stop on its own. Using timeout calls to simulate intermittent calls is generally considered the best pattern. True intermittent calls are rarely used in a development environment, because the latter one may be started after the previous one has finished. This can be avoided entirely, as in the previous example, so it is best not to use intermittent calls.

Location object

Location is one of the most useful BOM objects

Create a function that parses the query string and returns an object with all the parameters

Function getQueryStringArgs (url) {var qs = url.split('? ') [1]; Var args = {}, // get the first items = qs.length? Qs.split ('&') : [], item = null, name = null, value = null, // use I = 0, len = items.length; // Add each item one by one to the args object for (I = 0; i < len; I ++) {item = items[I].split('=') name = decodeURIComponent(item[0]) // decodeURIComponent decodeURIComponent Value = decodeURIComponent(item[1]) if (name.length) {args[name] = value}} return args} let url = 'https://zhidao.baidu.com/question/1768422895052400180.html?fr=iks&word=slice&ie=gbk' console.log(getQueryStringArgs(url))Copy the code
The history object

History is a property of the Window object, so every browser window, every label, and even every frame has its own History object associated with a particular Window object.

Use the go() method to jump through the user’s history, either backwards or forwards. This method takes an integer value representing the number of pages that jump back or forward. A negative number means a backward jump (similar to clicking the browser’s back button) and a positive number means a forward jump

History. go(1) // forward one page history.go(-1) // backward one pageCopy the code

You can also pass a string argument to go(), at which point the browser jumps to the first position in history that contains the string — either backwards or forwards, depending on which position is closest. If the string is not in the history, then this method does nothing

Go ('wrox.com') // Jump to the nearest wrox.com pageCopy the code

Alternatively, instead of go(), you can use back() and forward(), which, as the name suggests, mimic the browser’s back and forward buttons

History.back () // back a page history.forward() // forward a pageCopy the code

The history object also has a Length property that holds the number of history records, including all history records, that is, all forward and backward records. For the first page loaded into a window, TAB, or frame, history.length is 0, and you can determine if the user opened your page in the first place by testing the value of this property as shown below

If (history.length == 0) {// This should be the first page after the user opens the window}Copy the code
summary

The Browser Object Model (BOM), based on the Window object, represents the browser window and the visible area of the page. Also, the Window object has ECMAScript’s Global object, so all Global variables and functions are its properties, and all native constructors and other functions live in its namespace.