
'use strict' "use strict" , and the same directive, followed by a semicolon ( 'use strict'; and "use strict"; ), will also have the effect. This directive (exactly like this, along with quotes), so that all code in a certain file would be executed in strict mode, is placed at the beginning of this file. 'use strict' const name = 'Flavio' const hello = () => 'hey' //... function hello() { 'use strict' return 'hey' } ;(function() { variable = 'hey' })() variable will be available in the global scope after running IIFE. ;(function() { 'use strict' variable = 'hey' })() undefined . In the usual JS such a command is quite possible. undefined = 1 undefined , but in reality it is an attempt to write a new value to a property of a global object, which, by the way, according to the standard, cannot be overwritten. In normal mode, although such a command is possible, it will lead to nothing - that is, the value of undefined will not be changed, and the error message will not appear. In strict mode, this will cause an error. In order to see this error message, and at the same time make sure that the value undefined not overridden in the normal mode, try the following code in a browser or in Node.js. undefined = 1 console.log('This is '+undefined) ;(() => { 'use strict' undefined = 1 })() Infinity and NaN , as well as with other similar ones. Strict mode allows you to avoid all this. const car = {} Object.defineProperty(car, 'color', { value: 'blue', writable: false }) console.log(car.color) car.color = 'yellow' console.log(car.color) writable: false attribute used when setting the color property.color object or to an error output. An attempt to change this property in strict mode will end with an error. ;(() => { 'use strict' car.color = 'red' })() const car = { get color() { return 'blue' } } console.log(car.color) car.color = 'red' console.log(car.color) ;(() => { 'use strict' car.color = 'yellow' } )() const car = { color: 'blue' } Object.preventExtensions(car) console.log(car.model) car.model = 'Fiesta' console.log(car.model) model object will result in the console undefined value undefined . There was no such property in the object; an attempt to create it after the object was made non-expandable did not lead to anything. The same action in strict mode results in an error message. ;(() => { 'use strict' car.owner = 'Flavio' } )() let one = 1 one.prop = 2 console.log(one.prop) 1 cannot create the prop property. Similarly, the system behaves when working with other primitive data types.delete simply returns false and everything will silently end in failure. delete Object.prototype ;(function(a, a, b) { console.log(a, b) })(1, 2, 3) //2 3 2 3 . In strict mode, this will cause an error.0 to the beginning. ;(() => { console.log(010) })() //8 10 , that is 8 will fall into the console. This 0 before the number can be set randomly. In strict mode, octal numbers specified in this format cannot be operated. But if you need to use strict mode and work with octal numbers, you can write them in the format 0oXX . The following code will also output 8 . ;(() => { 'use strict' console.log(0o10) })() //8 this , which we have already encountered, behaves differently and which we will now discuss in more detail.this , or execution context, allows us to describe the environment in which JS code is executed. Its value depends on the place of its use and on whether strict mode is enabled or not.this passed to the function is not cast to the object. This transformation not only requires resources, but also gives functions access to the global object if they are called with this set to undefined or null . This behavior means that the function can gain unauthorized access to the global object. In strict mode, the conversion of this to the function is not performed. In order to see the difference between this behavior in functions in different modes - try this code using the 'use strict' directive and without it. ;(function() { console.log(this) })() this in such a function refers to this object. This statement can be illustrated by the following example. const car = { maker: 'Ford', model: 'Fiesta', drive() { console.log(`Driving a ${this.maker} ${this.model} car!`) } } car.drive() //Driving a Ford Fiesta car! this , used in which, is automatically attached to the object containing this function. const car = { maker: 'Ford', model: 'Fiesta', drive: function() { console.log(`Driving a ${this.maker} ${this.model} car!`) } } this in the object method can also be observed using the following construct. const car = { maker: 'Ford', model: 'Fiesta' } car.drive = function() { console.log(`Driving a ${this.maker} ${this.model} car!`) } car.drive() //Driving a Ford Fiesta car! const car = { maker: 'Ford', model: 'Fiesta', drive: () => { console.log(`Driving a ${this.maker} ${this.model} car!`) } } car.drive() //Driving a undefined undefined car! undefined are displayed. The fact is that, as we have said, this in the arrow function contains a link to the context that includes the function.this to an arrow function, and you canthis . This can be done in different ways. For example, when declaring a function, you can bind its this keyword to an object using the bind() method. const car = { maker: 'Ford', model: 'Fiesta' } const drive = function() { console.log(`Driving a ${this.maker} ${this.model} car!`) }.bind(car) drive() //Driving a Ford Fiesta car! this , you can bind another object. const car = { maker: 'Ford', model: 'Fiesta', drive() { console.log(`Driving a ${this.maker} ${this.model} car!`) } } const anotherCar = { maker: 'Audi', model: 'A4' } car.drive.bind(anotherCar)() //Driving a Audi A4 car! call() and apply() methods. const car = { maker: 'Ford', model: 'Fiesta' } const drive = function(kmh) { console.log(`Driving a ${this.maker} ${this.model} car at ${kmh} km/h!`) } drive.call(car, 100) //Driving a Ford Fiesta car at 100 km/h! drive.apply(car, [100]) //Driving a Ford Fiesta car at 100 km/h! this bound to what is passed to these methods as the first argument. The difference between these methods is that apply() , as the second argument, takes an array with the arguments passed to the function, and call() takes a list of arguments.this points to the HTML element with which this or that event occurred. In order to bind to a callback, as this , something else, you can use the bind() method. Here is an example illustrating this. <!DOCTYPE html> <html> <body> <button id="el">Element (this)</button> <button id="win">Window (this</button> <script> const el = document.getElementById("el") el.addEventListener('click', function () { alert(this) //object HTMLButtonElement }) const win = document.getElementById("win") win.addEventListener('click', function () { alert(this) //object Window }.bind(this)) </script> </body> </html> onclick event that occurs when a button is clicked is assigned to a button labeled Button 1 . <!DOCTYPE html> <html> <body> <button onclick="alert('Button 1!')">Button 1</button> <button onclick="doSomething()">Button 2</button> <script> function doSomething(){ const str = 'Button 2!' console.log(str) alert(str) } </script> </body> </html> Button 2 takes a similar approach, but it indicates the function that is executed in response to the button being pressed. This code outputs the specified string to the console and displays a window with the same text.window object has an onload that is triggered after loading the HTML code of the page and all the additional resources it needs, for example, styles and images. If you assign a handler to this event, then when you call it, you can be sure that the browser has loaded all the contents of the page, with which you can now work programmatically, without fear that some page elements have not yet been loaded. window.onload = () => { alert('Hi!') // } readyState property changes state. Here is an example of using this approach to load JSON data from a public API. <!DOCTYPE html> <html> <body> <button onclick="loadData()">Start</button> <script> function loadData (){ const xhr = new XMLHttpRequest() const method = 'GET' const url = 'https://jsonplaceholder.typicode.com/todos/1' xhr.open(method, url, true) xhr.onreadystatechange = function () { if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { console.log(xhr.responseText) } } xhr.send() } </script> </body> </html> if (window.onload){} addEventListener() method, which we have already met, is a modern mechanism for assigning event handlers. It allows you to register multiple handlers for one event. window.addEventListener('load', () => { // }) addEventListener() method. It uses a similar attachEvent() method. This should be taken into account if your program must support legacy browsers.window object to handle "global" events, such as keystrokes on the keyboard. At the same time, individual HTML elements are assigned event handlers that react to what happens to these elements, for example, mouse clicks. Therefore, the addEventListener() method is used with both the window object and ordinary elements.Event . The set of properties of this object depends on the event that it describes. Here, for example, is a code that demonstrates handling keyboard keystroke events keydown window keydown event. <!DOCTYPE html> <html> <body> <script> window.addEventListener('keydown', event => { // console.log(event.type, event.key) }) window.addEventListener('mousedown', event => { // //0 - , 2 - console.log(event.type, event.button, event.clientX, event.clientY) }) </script> </body> </html> key object is used. The type property is also used here, indicating the type of event. In this example, in fact, we are working with a KeyboardEvent object, which is used for descriptions of keyboard-related events. This object is an inheritor of the Event object. Objects designed to handle a variety of events extend the capabilities of the standard event object.mousedown event handler, we display the event type, button number ( button property) and pointer coordinates at the time of the click ( clientX and clientY ) to the clientY .Event object that are available in other event objects are the already mentioned type property and the target property, indicating the DOM element on which the event occurred. The Event object has methods. For example, the createEvent() method allows you to create new events. <!DOCTYPE html> <html> <head> <style> #container { height: 100px; width: 200px; background-color: blue; } #child { height: 50px; width: 100px; background-color: green; } </style> </head> <body> <div id="container"> <div id="child"> </div> </div> <script> const contDiv = document.getElementById('container') contDiv.addEventListener('click', event => { console.log('container') }) const chDiv = document.getElementById('child') chDiv.addEventListener('click', event => { console.log('child') }) window.addEventListener('click', event => { console.log('window') }) </script> </body> </html> window container window child container window 
stopPropagation() can be stopped using the stopPropagation() method of the stopPropagation() object. For example, if it is necessary that, after clicking the child element, the corresponding event does not extend further, we need to rewrite the code in which we assign it a click event handler, as follows. chDiv.addEventListener('click', event => { console.log('child') event.stopPropagation() }) container , — child , . window container window child load window . , , HTML- body .click . dblclick — . click dblclick , click , — dblclick . mousedown , mousemove , mouseup , . , mousemove , , , . , - , . .keydown . , . — keyup .scroll window . , , , window.scrollY .mousemove , .mousemove scroll . - . . «» (throttling), Lodash . , , , , . . let cached = null window.addEventListener('mousemove', event => { if (!cached) { setTimeout(() => { // cached console.log(cached.clientX, cached.clientY) cached = null }, 100) } cached = event }) mousemove , 100 . import package from 'module-name' const package = require('module-name') export keyword. , , , , uppercase.js . . export default str => str.toUpperCase() <script> type="module" . <script type="module" src="index.js"></script> uppercase.js , , , . -. , -. , VSCode, Live Server ( — ritwickdey.liveserver). <!DOCTYPE html> <html> <head> </head> <body> <script type="module"> import toUpperCase from './uppercase.js' console.log(toUpperCase('hello')) </script> </body> </html> HELLO . import toUpperCase from 'https://flavio-es-modules-example.glitch.me/uppercase.js' ./ / . export default str => str.toUpperCase() const a = 1 const b = 2 const c = 3 export { a, b, c } module.js , , , . <html> <head> </head> <body> <script type="module"> import * as m from './module.js' console.log(ma, mb, mc) </script> </body> </html> 1 2 3 . import { a } from './module.js' import { a, b } from './module.js' console.log(a) import { a, b as two } from './module.js' module.js . const a = 1 const b = 2 const c = 3 export { a, b, c } export default () => console.log('hi') import sayHi, { a } from './module.js' console.log(a) sayHi() Access-Control-Allow-Origin: * ).nomodule . , , . <script type="module" src="module.js"></script> <script nomodule src="fallback.js"></script> up-node.js . exports.uppercase = str => str.toUpperCase() const up = require('./up-node.js') console.log(up.uppercase('hello')) HELLO . const package = require('module-name') exports.a = 1 exports.b = 2 exports.c = 3 const { a, b, c } = require('./up-node.js') Math , . , , JS- .+ . : const three = 1 + 2 //3 const four = three + 1 //4 'three' + 1 // three1 const two = 4 - 2 //2 20 / 5 //4 20 / 7 //2.857142857142857 Infinity ( ) - Infinity ( ). 1 / 0 //Infinity -1 / 0 //-Infinity % , . 20 % 5 //0 20 % 7 //6 NaN (Not a Number — ). 1 % 0 //NaN -1 % 0 //NaN 1 * 2 //2 -1 * 2 //-2 1 ** 2 //1 2 ** 1 //2 2 ** 2 //4 2 ** 8 //256 8 ** 2 //64 ++ 1 . .1 , . let x = 0 ++x //1 x //1 let x = 0 x++ //0 x //1 -- ++ , 1 , . let x = 0 x-- //0 x //-1 --x //-2 let x = 2 -x //-2 x //2 let x = 2 +x //2 x = '2' +x //2 x = '2a' +x //NaN = ), , . , , += . let x = 2 x += 3 x //5 let x = 2 x = x + 3 x //5 -=*=/=%=**= const a = 1 * 2 + 5 / 2 % 2 2.5 . , . , .- + ++ -- — ,/ % — , ,+ - —= += -= *= /= %= **= — const a = 1 * 2 + 5 / 2 % 2 const a = 2 + 2.5 % 2 const a = 2 + 0.5 const a = 2.5 const a = 1 * (2 + 5) / 2 % 2 1.5 .Math , . . , .Math.E — , e, Math.PI — , π. Math.E // 2.718281828459045 Math.PI //3.141592653589793 Math.abs() —Math.ceil() — , ,Math.cos() — ,Math.floor() — , ,Math.max() —Math.min() —Math.random() — [0, 1) ( 1)Math.round() —Math.sqrt() —== — . .!= — .=== —!== —< — «»> — «».<= — « ».>= — « ». 1 === true //false 1 == true //true 1 true . 1 true , 1 true .
Source: https://habr.com/ru/post/431072/
All Articles