Tips and Tricks that you may need to know when you work in JavaScript(Q&A)

If so, how?In JavaScript, all numbers are presented for use in a string view and there are no built-in tools for working with binary data.

There is the BinaryParser JavaScript library for working with binary numbers: encoding, decoding (its code is hell!)In ECMAScript 6+ (strawman) there is a StructType draft (this is a struct familiar to us from C++ and others).

It is needed to simplify working with binary files.

Here is how it might look in the future:const Point2D = new StructType({ x: uint32, y: uint32 });const Color = new StructType({ r: uint8, g: uint8, b: uint8 });const Pixel = new StructType({ point: Point2D, color: Color });const Triangle = new ArrayType(Pixel, 3);let t = new Triangle([{ point: { x: 0, y: 0 }, color: { r: 255, g: 255, b: 255 } }, { point: { x: 5, y: 5 }, color: { r: 128, g: 0, b: 0 } }, { point: { x: 10, y: 0 }, color: { r: 0, g: 0, b: 128 } }]);14.

How to change context variables of another function from one function?You can give a reference to the primer context object in smthPass the function generated in the primer context to the smth functionvar primer = function () { var a, b, c, d, e = {};smth (function () { a = 1; b = 2; c = 3; d = 4; }, e);alert ([a, b, c, d, e.

pewpew]);},smth = function (callback, e) { callback (); e.

pewpew = "pewpew";};primer ();3.

Previously (FireFox 3.

6-) it was possible to reach the context through __parent__, but in version 4 we saw this feature out.

15.

Regarding the article “Five ways to call a function.

” Which of these N methods (in heading 5, in article 4, a few in the comments) when to use better and why?I will not consider the global call/method call and constructor, their scope is clear.

I will stop separately on call and apply.

They do the same thing — they call the function with the explicit context this.

1.

Сall and apply for the designer override:// Auxiliary functionfunction extend (newObj, oldObj) {function F () {} F.

prototype = oldObj.

prototype; newObj.

prototype = new F (); return newObj}var Obj = function () { this.

obj_var = 100;};Obj.

prototype.

obj_proto_var = 101;var NewObj = function () { Obj.

call (this); // Call the Obj constructor and get the Own property obj_var this.

new_obj_var = 102;};extend (NewObj, Obj)NewObj.

prototype.

new_obj_proto_var = 103;new NewObj (); // {new_obj_proto_var: 103, new_obj_var: 102, obj_proto_var: 101, obj_var: 100}2.

Transformation of arguments NodeList and other array-like objects to an array, transformation of a live list (getElementsByTagName) to an array.

// document.

getElementsByTagName ("div") does not return an array (although it is similar), so we cannot execute array methodsdocument.

getElementsByTagName ("div").

forEach (function (elem) { // .

}); // TypeError: document.

getElementsByTagName ("div").

ForEach is not a function// Lead to an array: we slip the fuction function slice this, which is a trip to the arrayArray.

prototype.

slice.

call (document.

getElementsByTagName ("div")).

ForEach (function (elem) { // OK});// Similarly, you can do with stringsArray.

prototype.

slice.

call ('pewpew') // ["p", "e", "w", "p", "e", "w"]// In IE8, there will be an array from undefined3.

Tricks with Function.

call.

apply for creating wrappers:We need to write a wrapper foo () that calls bar () in the specified context with an arbitrary number of arguments.

In a traditional way, it would look like this:function bar () {}// foo (context, arg1, arg2, .

)function foo () { var context = arguments [0]; var args = Array.

prototype.

slice.

call (arguments, 1); // make an array of arguments for bar bar.

apply (context, args);}Instead of this salad use the trick with call.

apply:function foo() { Function.

call.

apply(bar, arguments);}It works like this: aplly calls Function.

call on the bar object with the parameters passed to foo.

That is, we get the following for the very first example with context and arg1, arg2:bar.

call(context, arg1, arg2)4.

Emulation16.

How to transfer the scope of execution of one function to another?No Previously (FireFox 3.

6-) it was possible to reach the context through __parent__, but in version 4 we saw this feature.

17.

How correctly to receive global object without its direct instructions, without eval and at ‘use strict’?No, if you omit one of the conditions, or execute only in the global scope, you can:// 1: eval – on(function () { "use strict"; var globalObject = (0, eval) ("this"); // Magic 🙂 return globalObject;} ());// 2: specify the name – on(function (global) { // .

} (window));// 3: "use strict" – off(function () { return this;} ());// 4: If we execute this code in globals, we will get a reference to a global variable, but otherwise it will not work.

// This is the best option"use strict";(function (global) { // global}) (this);18.

Is it possible to restart the event in javascript after intercepting the event?The event does not carry any load; it is just an event descriptor.

But you can explicitly pass a reference to the event handler, like this:$ ('# smth').

click (function onSmthClick (event) { if (smth) { // Write handler event.

handlerFunction = onSmthClick; event.

handlerContext = this; // pass to the left object // now otherObjectSetSomeEvent can use event.

handlerFunction and call the handler otherObjectSetSomeEvent (event); } else { // do something else }});But this is not a good solution, because will have a lot of extra stuff to the wind.

And the logic is very confusing.

It is better to alter the logic and divide the general handler into 2 parts:$ ('# smth').

click (function handler1 (event) { if (smth) { // pass to the left object leftObjectSetSomeEvent (event, function handler2 (e) { // do something with event or e }); } else { // do something else }});function leftObjectSetSomeEvent (event, callback) { callback (event); // do something with the event}19.

How on JS to intercept all clicks on the page for any elements?.That is, make a single handler for clicksIt is necessary to hang up the click event handler on the lowest object in the DOM tree, all clicks on the elements will “pop up” (if the traffic cops are not slowed down, by the way, prohibiting ascent) before it.

// jQuery$ (window) .

bind ('click', function (e) { console.

log ('Clicked on', e.

target);});// You can also limit it to some area using jQuery delegate$ ('# pewpew').

delegate ('*', 'click', function (e) { console.

log ('Clicked on', e.

target);});// You can limit goals$ ('# pewpew').

delegate ('.

pewpew', 'click', function (e) { console.

log ('Clicked on element with .

pewpew class name');});20.

How to run XHR without jQuery?Non-cross browser feature:function xhr(m,u,c,x){with(new XMLHttpRequest)onreadystatechange=function(x){readyState^4||c(x.

target)},open(m,u),send(с)}Cross browser slightly longer:function xhr(m,u,c,x){with(new(this.

XMLHttpRequest||ActiveXObject)("Microsoft.

XMLHTTP"))onreadystatechange=function(x){readyState^4||c(x)},open(m,u),send(с)}Using:xhr('get', '//google.

com/favicon.

ico', function(xhr){console.

dir(xhr)});21.

Reflow, repaint, and methods to minimize themIf the browser supports the requestAnimationFrame function, then you should use it instead of setInterval/setTimeoutBrowsers can optimize the animations going simultaneously, reducing the number of reflows and repaint to one, which in turn will lead to an increase in the accuracy of the animation.

For example, animations on JavaScript synchronized with CSS transitions or SVG SMIL.

Plus, if the animation is performed in a tab that is invisible, browsers will not continue to redraw, which will lead to less CPU, GPU, memory usage and as a result will reduce battery consumption in mobile devices.

2.

Avoid a large number of float elements (decrease reflow)4.

Modify the DOM tree as rarely as possible — write-in memory, and then insert it into the DOM 1 time (reflow will decrease)5.

Change the properties of an object with a bundle (decrease reflow, redraw) (this is not true for modern browsers)// Insteadelement.

style.

left = "150px;";// .

element.

style.

color = "green";// Change all at onceelement.

setAttribute ('style', 'color: green; left: 150px');6.

Drag animations with absolutely positioned objects only (reflow will decrease)7.

Before changing the group of elements, hide them style.

display = “none” (decreases reflow) (this is not true for modern browsers)Not on the topic, but also about optimization:8.

Use event delegation to reduce their number.

9.

Cache references to DOM elements (selector call is the most expensive operation)10.

Use the quick selector functions of querySelectorAll () firstElementChild11.

Remember that document.

getElementsByTagName returns a live collection of elements (if an element is added to the DOM tree, the collection will receive it automatically)In many modern browsers, these methods will not give such a visible advantage (browser developers are all optimizing for us).

22.

Should I use childProcesses in node.

js for each request in high-load projects?In no case should you use childProcesses for each request because we get too much overhead (it’s like PHP with Apache): allocating extra memory, fork time, initialization time (jid compilation), CPU load, etc.

Node.

js distributes the load very well and loads one processor core in its “event processing loop” — the main application thread.

Ideal download for Node.

js — 1 fork per core, best forked using Cluster.

The cluster will act as a balancer (masters), and forks — slaves.

Use childProcesses for heavy requests is justified.

25.

Using runInNewContext in node.

jsWhat is runInNewContext?I see the only application of this technology for launching someone else’s, potentially dangerous code (this is how Noter.

js hosting nodester does).

If there is no critical need for this, then I am categorically against it — this is an absolutely unnecessary wrapper, which you can not use if you choose the right application architecture and use agreements during development.

What is bad: the creation/deletion of context — memory allocation as a consequence of frequent GC (which blocks the entire application).

I think there will be problems with the support of such code.

.

. More details

Leave a Reply