I have a problem with understanding the prototype model, I got used to the “classical” class :) but decided to study JS. Please, if possible, write an article where, in the form of patterns, explain the possible options for constructing “classes”, different levels of visibility of methods and variables. I understand that such articles can be found in a huge number of ve, I understand that in JS, levels of visibility are “not needed”.
If with new, then how are you protected from errors:
1. Functions constructors I always write with a capital letter;
2. Check the validity of the creation through this instanceof Function_Name (I avoid this instanceof arguments.callee for performance reasons)
3. Similar to the second one, but I check with the window, since I do not want to hardcode the name and do not write scripts for out-of-browser environments.
var Obj = function () { "use strict"; this.pew = 100; }; // new Obj.pew++; // Obj(); // TypeError: this is undefined
// : , , use strict var Obj = function () { "use strict"; this.pew = 100; }; // : var Obj = function () { if (!(this instanceof Obj)) { return new Obj(); } this.pew = 100; };
mousedown mouseup
event mousedown mouseup
triggered by all mouse buttons, the click
is just the left one. In the event handler, you need to check the code of the event.button
button to find out which one was pressed: var button = document.getElementById('button'), // 0 1 2 buttonMap = ['Left', 'Middle', 'Right'], handler = function (event) { event = event || window.event; alert(buttonMap[event.button] + ' id: ' + event.button); }; if (button.addEventListener) { button.addEventListener('mousedown', handler, false); } else { // IE 0 1 2 3 4 buttonMap = ['???', 'Left', 'Right', '???', 'Middle']; button.attachEvent('onmousedown', handler); }
event.which
instead of magic with event.button
$('button').mousedown(function (event) { alert(['Left', 'Middle', 'Right'][event.which]); });
Is it possible to intercept keyboard key press events (down arrow, up) in javascript, so that the browser does not scroll the window after that? Are there any features among browsers in this behavior, if at all possible? For example, there is a table that does not fit onto the screen entirely, while moving through the rows is implemented using the arrow keys. It is necessary that the browser does not flip through this page.
form.submit()
is form.submit()
, when clicked on input, it will receive focus, when clicked the browser will click on the link, etc. // keypress, keyup $(window).bind($.browser.opera ? 'keypress' : 'keyup', function (event) { event.preventDefault(); // return false; });
preventDefault()
before defaultAction is executed. For example, when clicking on input, we do not want to transfer focus to it, then we need to hang the handler on an event in the chain before defaultAction - mousedown is executed. $('input').bind('mousedown', function (event) { event.preventDefault(); // return false; });
event.preventDefault()
: $(document).bind($.browser.webkit ? 'keydown' : 'keypress', function (event) { // Esc if ((event.which || event.keyCode) === 27) { event.preventDefault(); // return false; } });
function () { // source }()
function foo() { // source }()
!function () { // source }(); +function () { // source }(); [function() { // source }()]; var a = function () { // source }();
It is used incl. in jQuery. Allows you to select all the code in one block with a local scope. This speeds up access to internal variables, allows for cluttering up the global namespace and, more importantly, is compressed better by minifiers. habrahabr.ru/blogs/jquery/118564
The server sends the response “alert ('Boom !!!');” to user actions in the ajax system. On the client, the received response is run through eval () and executed. What is the name of such data transfer? This is not JSON, not XML, not HTML.
function timedProcessArray(items, process, callback) { var todo = items.concat(); //create a clone of the original setTimeout(function () { var start = +new Date(); do { process(todo.shift()); } while (todo.length > 0 && (+new Date() - start < 50)); if (todo.length > 0){ setTimeout(arguments.callee, 25); } else { callback(items); } }, 25); } function saveDocument(id) { var tasks = [openDocument, writeText, closeDocument, updateUI]; timedProcessArray(tasks, [id], function(){ alert("Save completed!"); }); }
timedProcessArray
function blocks the UI Threed for 25 ms, performing a chain of actions, then releases the UI Threed for 25 ms and so on. var time = 0, timerId, TIME_ADMISSION = 100; // 0.1s function onresizeend () { console.log('onresizeend'); }; function resizeWatcher () { if (+new Date - time >= TIME_ADMISSION) { onresizeend(); if (timerId) { window.clearInterval(timerId); timerId = null; } } }; $(window).resize(function () { if (!timerId) { timerId = window.setInterval(resizeWatcher, 25); } time = +new Date; });
window.open('http://www.google.com', '_blank', 'toolbar=0,location=0,menubar=0');
window.open('http://www.google.com');
Ctrl+Shift/Meta+Shift
always opens a new tab (regardless of the settings). To open a new tab, we will emulate the “click” event with Ctrl+Shift/Meta+Shift
: function safariOpenWindowInNewTab(href) { var event = document.createEvent('MouseEvents'), mac = (navigator.userAgent.indexOf('Macintosh') >= 0); // Ctrl+Shift+LeftClick/Meta+Shift+LeftClick () // event.initMouseEvent( /* type */ "click", /* canBubble */ true, /* cancelable */ true, /* view */ window, /* detail */ 0, /* screenX, screenY, clientX, clientY */ 0, 0, 0, 0, /* ctrlKey */ !mac, /* altKey */ false, /* shiftKey */ true, /* metaKey */ mac, /* button */ 0, /* relatedTarget */ null ); // - $('<a/>', {'href': href, 'target': '_blank'})[0].dispatchEvent(event); }
function object(o) { function F() {} F.prototype = o; return new F(); } var newObject = object(oldObject);
var cloner = { _clone: function _clone(obj) { if (obj instanceof Array) { var out = []; for (var i = 0, len = obj.length; i < len; i++) { var value = obj[i]; out[i] = (value !== null && typeof value === "object") ? _clone(value) : value; } } else { var out = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { var value = obj[key]; out[key] = (value !== null && typeof value === "object") ? _clone(value) : value; } } } return out; }, clone: function(it) { return this._clone({ it: it }).it; } }; var newObject = cloner.clone(oldObject);
// var newObject = jQuery.extend({}, oldObject); // var newObject = jQuery.extend(true, {}, oldObject);
var a = {z: 'z'}; var b = a; var c = a; delete az; delete a; // "" console.log(b, c); // : Object {} Object {},
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 } }]);
var 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();
// function 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); // Obj 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}
// document.getElementsByTagName("div") ( ), document.getElementsByTagName("div").forEach(function (elem) { // ... }); // TypeError: document.getElementsByTagName("div").forEach is not a function // : slice this, Array.prototype.slice.call(document.getElementsByTagName("div")).forEach(function (elem) { // OK }); // Array.prototype.slice.call('pewpew') // ["p", "e", "w", "p", "e", "w"] // 8- undefined
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); // bar bar.apply(context, args); }
Salad use trick with call.apply instead:
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)
// 1: eval - on (function(){ "use strict"; var globalObject = (0, eval)("this"); // :) return globalObject; }()); // 2: - on (function(global){ // ... }(window)); // 3: "use strict" - off (function(){ return this; }()); // 4: , , . // "use strict"; (function(global){ // global })(this);
$('#smth').click(function onSmthClick(event){ if (smth) { // event.handlerFunction = onSmthClick; event.handlerContext = this; // // otherObjectSetSomeEvent event.handlerFunction otherObjectSetSomeEvent(event); } else { // - } });
$('#smth').click(function handler1(event) { if (smth) { // leftObjectSetSomeEvent(event, function handler2(e) { // - event e }); } else { // - } }); function leftObjectSetSomeEvent(event, callback) { callback(event); // - event }
// jQuery $(window).bind('click', function (e) { console.log('Clicked on ', e.target); }); // - , jQuery delegate $('#pewpew').delegate('*', 'click', function (e) { console.log('Clicked on ', e.target); }); // $('#pewpew').delegate('.pewpew', 'click', function (e) { console.log('Clicked on element with .pewpew class name'); });
function xhr(m,u,c,x){with(new XMLHttpRequest)onreadystatechange=function(x){readyState^4||c(x.target)},open(m,u),send()}
function xhr(m,u,c,x){with(new(this.XMLHttpRequest||ActiveXObject)("Microsoft.XMLHTTP"))onreadystatechange=function(x){readyState^4||c(x)},open(m,u),send()}
xhr('get', '//ya.ru/favicon.ico', function(xhr){console.dir(xhr)});
I wanted to learn about working with the file system through JavaScript, for example, to read and write to files. Most textbooks describe JavaScript for browsers, where working with files is not needed, but for example in a server application or, for example, XUL is a necessity, but there is very little documentation, if at all.
requestAnimationFrame
function, then you should use it instead of setInterval/setTimeout
Browsers can optimize the animations going simultaneously, reducing the number of reflow 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 you are animating in a tab that is invisible, browsers will not continue redrawing, 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)
// element.style.left="150px;"; //... element.style.color="green"; // element.setAttribute('style', 'color:green;left:150px');
style.display = "none"
(decreases reflow) (this is not true for modern browsers)Source: https://habr.com/ru/post/120192/
All Articles