Java Script

Материал из support.qbpro.ru

Как бы учебник



Крайне полезная информация

Это надо обработать

обработка событий в примерах

Контекст

Контексты исполнения

Библиотеки


Несколько интересных проектов с помощью которых можно динамически создавать векторные рисунки.

Полезные трюки

http://habrahabr.ru/post/155093/

Как работает Array.prototype.slice.call

Для того, чтобы из аргументов JavaScript функции "отрезать" первые Х значений, используется метод:

Array.prototype.slice.call(arguments, X);

Например такая функция вернет "3,4":

(function(){
  var args = Array.prototype.slice.call(arguments, 2);
  alert(args); // Returns: 3,4
})(1, 2, 3, 4);


Таким образом, такой подход используется когда нужно срезать входящие параметры функции JavaScript.

Array.prototype.concat.apply

Для объединения более двух массивов используется concat().

var a = [1, 2], b = ["x", "y"], c = [true, false];
var d = a.concat(b, c);
console.log(d); // [1, 2, "x", "y", true, false];

For concatenating just two arrays, using push.apply() can be used instead for the case of adding elements from one array to the end of another without producing a new array. With slice() it can also be used instead of concat() but there appears to be no performance advantage from doing this.

var a = [1, 2], b = ["x", "y"];
a.push.apply(a, b);
console.log(a); // [1, 2, "x", "y"];

Современный метод bind

В современном JavaScript для привязки функций есть метод bind. Он поддерживается большинством современных браузеров, за исключением IE<9, но легко эмулируется.

Этот метод позволяет привязать функцию к нужному контексту, и даже к аргументам.

Синтаксис bind:

var wrapper = func.bind(context[, arg1, arg2...])
  • func Произвольная функция
  • wrapper Функция-обёртка, которую возвращает вызов bind. Она вызывает func, фиксируя контекст и, если указаны, первые аргументы.
  • context Обертка wrapper будет вызывать функцию с контекстом this = context.
  • arg1, arg2, … Если указаны аргументы arg1, arg2... — они будут прибавлены к каждому вызову новой функции, причем встанут перед теми, которые указаны при вызове.

Простейший пример, фиксируем только this:

function f() {
  alert(this.name);
}

var user = { name: "Вася" };

var f2 = f.bind(user);

f2(); // выполнит f с this = user

Использование для привязки метода sayHi к новому объекту User:

function User() {
  this.id = 1;
  this.sayHi = function() {
    alert(this.id);
  }.bind(this);
}
var user = new User();
setTimeout(user.sayHi, 1000); // выведет "1"

Object.defineProperty или как сделать код капельку лучше

оригинал статьи тоже ребята старались

Этот краткий пост-заметку или температурный бред (в Одессе похолодало, да) хочу посвятить такой прекрасной функции, как Object.defineProperty (и Object.defineProperties). Активно использую её уже около двух месяцев, так как поддержка старых браузеров (в том числе и IE8) в проекте, который я сейчас реализую, не требуется (завидуйте).

Как положено статье на хабре, приведу краткое описание того, что она делает. Object.defineProperty добавляет новое свойство, обладающее неким нестандартным для обычного свойства поведением, и принимает три аргумента:

  • Объект, который мы модифицируем, добавляя новое свойство
  • Свойство (строка), которое, собственно, хотим добавить
  • Дескриптор: объект, содержащий «настройки» нового свойства, например аццессоры (геттер, сеттер)

Дескриптор может содержать следующие свойства:

  • value (любое значение: строка, функция...) — значение, которое получит определяемое свойство объекта (геттер и сеттер в данном случае определить нельзя)
  • writable (true/false) — можно ли перезаписать значение свойства (аццессоры тоже не доступны)
  • get (функция) — геттер (value и writable определить нельзя)
  • set (функция) — сеттер (value и writable определить нельзя)
  • configurable (true/false) — можно ли переопределить дескриптор (использовать Object.defineProperty над тем же свойством)
  • enumerable (true/false) — будет ли свойство перечисляться через for..in и доступно в Object.keys (плохая формулировка)
var o = {};
Object.defineProperty(o, "a", {value : 37,
                               writable : true,
                               enumerable : true,
                               configurable : true});

 
var bValue;
Object.defineProperty(o, "b", {get : function(){ return bValue; },
                               set : function(newValue){ bValue = newValue; },
                               enumerable : true,
                               configurable : true});

Лучше меня объяснит MDN Object/defineProperty. Благо, даже английский знать не надо, и так всё понятно.

Если нужно определить сразу несколько свойств, можно использовать Object.defineProperties, который принимает два аргумента: объект, требующий изменений и объект с определяемыми ключами. MDN: Object/defineProperties.

// Код сперт с MDN
Object.defineProperties(obj, {
  "property1": {
    value: true,
    writable: true
  },
  "property2": {
    value: "Hello",
    writable: false
  }
  // etc. etc.
});


Теперь соль. Чего я вообще решил это запостить?

Так как в упомянутом выше проекте мне приходится использовать defineProperty не просто активно, а очень активно, код стал, мягко говоря, некрасивым. Пришла в голову простейшая идея (как я до этого раньше-то не додумался?), расширить прототип Object, сделав код сильно компактнее. Плохой тон, скажете вы, засерать прототип Object новыми методами.

Откуда вообще взялось это мнение? Потому что все объекты унаследуют это свойство, которое, при обычной модификации прототипа, становится перечисляемым в for..in. На душе становится тепло, когда вспоминаешь о том, что я описал выше, а именно, о свойстве дескриптора enumerable. Действительно, расширив прототип таким образом:

Object.defineProperty( Object.prototype, 'logOk' {
    value: function() { console.log('ok') },
    enumerable: false
});

все объекты получат этот метод, но, при этом, он будет неперечисляемым (не нужно каждый раз использовать hasOwnProperty для проверки, есть ли такое свойство):

var o = {a: 1, b: 2}
for( var i in o ) console.log( i, o[ i ] );
> a 1
> b 2
o.logOk();
> ok


Собственно то, ради чего я тут графоманю.

Во-первых определим метод define, чтоб каждый раз не вызывать перегруженную, на мой взгляд, конструкцию. Во-вторых определим метод extendNotEnum, который расширяет объект неперечисляемыми свойствами.

Object.defineProperties( Object.prototype, {
    define: {
        value: function( key, descriptor ) {
            if( descriptor ) {
                Object.defineProperty( this, key, descriptor );
            } else {
                Object.defineProperties( this, key );
            }
            return this;
        },
        enumerable: false
    },
    extendNotEnum: {
        value: function( key, property ) {
            if( property ) {
                this.define( key, {
                    value: property,
                    enumerable: false,
                    configurable: true
                });
            } else {
                for( var prop in key ) if( key.hasOwnProperty( prop ) ){
                    this.extendNotEnum( prop, key[ prop ] );
                }
            }
        },
        enumerable: false
    }
});

Использование:

var o = { a: 1 };
o.define( 'randomInt', {
    get: function() {
        return 42;
    }
});

o.extendNotEnum({
    b: 2;
});

for( var i in o ) console.log( i, o[ i ] );
> a 1
> randomInt 42

console.log( o.b );
> 2

И пошла… Еще два удобных метода:

Object.prototype.extendNotEnum({
    extend: function() {
        var args = Array.prototype.slice.call( arguments );
        args.unshift( this );
        return $.extend.apply( null, args ); // если jQuery надоест, можно просто переписать под себя
    },
    
    each: function( callback ) {
        return $.each( this, callback ); // аналогично
    }
});


o.extend({c: 3}); // тупо добавляет новые свойства в объект
o.each(function( key, value ) {
    // просто повторяет механизм $.each, перебирая все ключи и свойства
});


Добавлять новые свойства можно до бесконечности, никто вам за это руку не откусит.

Вывод

Играйте в Денди, пишите на Javascript, который становится всё лучше и лучше.

комментарии


Еще один финт ушами для тех, кто определяет свойства прототипа только однажды, после определения функции-конструктора: // запускается в консоли Object.defineProperty( Object.prototype, 'awesomeprototype', { set: function( object ) { for( var prop in object ) { Object.defineProperty( this.prototype, prop, { value: object[ prop ], enumerable: false }); } } }); var X = function() {} X.awesomeprototype = { method: function() { alert( 'ok' ) } }; var x = new X x.method()

Стоит отметить что в литералах объектов свойства можно задавать через геттер и сеттер:

var o = {
    __someProperty : 42,
    get someProperty() { return this.__someProperty; },
    set someProperty(v) { this.__someProperty = v; }
};

o.someProperty; // 42
o.someProperty = 56;
o.someProperty; // 56

Ну это так, к слову :)

deferred

Шаблонизация в JavaScript

DOM

dom2json

http://coderepos.org/share/browser/lang/javascript/dom2json/dom2json.js?rev=30780 skips empty attributes that IE implicitly adds

/*
 * $Id: dom2json.js,v 0.2 2008/06/15 07:04:10 dankogai Exp dankogai $
 */
(function(){
   
dom2json = function(dom){
    var type = dom.nodeType;
	    if (type == 3) return dom.nodeValue;
	    if (type == 1){
	        var json = [];
	        json.push(dom.nodeName);
	        var attrs = dom.attributes;
	        if (attrs.length){
	            var attr = {};
	            for (var i = 0, l = attrs.length; i < l; i++){
	                attr[attrs[i].name] = attrs[i].value;
	            }
	            if (0 /*@cc_on +1@*/){
	                attr['style'] = dom.style;
	            }
	            json.push(attr);
	        }
	        if (! dom.hasChildNodes()) return json;
	        var kids = dom.childNodes;
	        for (var i = 0, l = kids.length; i < l; i++){
	            var kjson = arguments.callee(kids[i]);
	            if (kjson) json.push(kjson);
	        }
	        return json;
	    }
	};
	
	json2dom = function(json){
	    var i = 0;
	    var tag = json[i++]
	    var dom = document.createElement(tag);
	    if (json[i].constructor == Object){
	        var attr = json[i++];
	        for (var name in attr){
	            dom.setAttribute(name, attr[name]);
	        }
	    }
	    for (var l = json.length; i < l; i++){
	        dom.appendChild(
	            json[i].constructor == Array
	                ? arguments.callee(json[i])
	                : document.createTextNode(json[i])
	            );             
	    }
	    return dom;
	}
	
	})();

обход дерева DOM

 /**
 * Рекурсивное перечисление дочерних элементов
 *
 * @param DomNode node
 * Родительский элемент, чьи дочерние узлы нужно перечислять.
 *
 * @return void
 */
function enumChildNodes(node) {
    // если нам передали элемент
    if (node && 1 == node.nodeType) {
        // берем его первый дочерний узел
        var child = node.firstChild;
        // пока узлы не закончились
        while (child) {
            // если этот узел является элементом
            if (1 == child.nodeType) {
                // что-то делаем с найденным элементом
                alert('элемент ' + child.tagName);
                // рекурсивно перечисляем дочерние узлы
                enumChildNodes(child);
            };
            // переходим к следующему узлу
            child = child.nextSibling;
        };
    };
};
 
// перечисляем содержимое body
enumChildNodes(document.body);

Обход child nodes (потомков) определнного элемента в Javascript

JavaScript на заметку Комментировать Речь о том как корректно обойти элементы потомки DOM для данного элемента, простите за тафтологию

var object = document.getElementById('el');
for (var childItem in object.childNodes) {
if (object.childNodes[childItem].nodeType == 1)
object.childNodes[childItem].style.color = '#FF0000';

В данном примере мы берем некоторый элемент с id = 'el' и проходим по массиву его потомков (childNodes), при этом проверяем nodeType потомка, чтобы он был элементом страницы и если так, то окрашиваем его в КРАСНЫЙ цвет.

В принципе на базе этой конструкции можно организовать рекурсивный обход дерева всех потомков заданного элемента, если конечно возникнет такая необходимость, но пока я представляю только упрощенный вариант.

Здесь следует обратить внимание на проверку свойства nodeType == 1, дело в том что без этой проверки в обработку попадут и разрывы строк, т.е. символы "\n", которые тоже воспинимаются как ноды. Т.е. например конструкция вида:

так быстрее и меньше кода

var object = document.getElementById(‘el’).getElementsByTagName(‘*’);
for(var i=0;object[i];i++){
object[i].style.color = ‘#FF0000′;


Sun, getElementsByTagName не поддерживает ИЕ, смысл его использовать?

К сожалению заметил, что данная конструкция в Opera выполняется некорректно (цикл for проходится два раза), никто с таким не встречался? Где-то всё же закралась моя ошибка или это ошибка браузера (проверял в 9.20, 9.50, 10.20), замечу, что в остальных браузерах всё выполняется верно.

var object = document.getElementById(‘el’);
for (var childItem in object.childNodes) {

}

var object=document.getElementById(‘el’);
for(var i=0;i<object.childNodes.length;i++) {
if (object.childNodes[i].nodeType == 1) {
// тут что-либо делаем
}
}

Functional JavaScript

Источник

Each post will cover a specific aspect of functional programming in JavaScript.

Tuesday, July 16, 2013 Functors Consider the function below.

function plus1(value) {

   return value + 1  

} It is just a function that takes an integer and adds one to it. Similarly we could could have another function plus2. We will use these functions later.

function plus2(value) {

   return value + 2  

} And we could write a generalised function to use any of these functions as and when required.

function F(value, fn) {

   return fn(value)  

}

F(1, plus1) ==>> 2 This function will work fine as long as the value passed is an integer. Try an array.

F([1, 2, 3], plus1) ==>> '1,2,31' Ouch. We took an array of integers, added an integer and got back a string! Not only did it do the wrong thing, we ended up with a string having started with an array. In other words our program also trashed the structure of the input. We want F to do the "right thing". The right thing is to "maintain structure" through out the operation.

So what do we mean by "maintain structure"? Our function must "unwrap" the given array and get its elements. Then call the given function with every element. Then wrap the returned values in a new Array and return it. Fortunately JavaScript just has that function. Its called map.

[1, 2, 3].map(plus1) ==>> [2, 3, 4] And map is a functor!

A functor is a function, given a value and a function, does the right thing.

To be more specific. A functor is a function, given a value and a function, unwraps the values to get to its inner value(s), calls the given function with the inner value(s), wraps the returned values in a new structure, and returns the new structure.

Thing to note here is that depending on the "Type" of the value, the unwrapping may lead to a value or a set of values.

Also the returned structure need not be of the same type as the original value. In the case of map both the value and the returned value have the same structure (Array). The returned structure can be any type as long as you can get to the individual elements. So if you had a function that takes and Array and returns value of type Object with all the array indexes as keys, and corresponding values, that will also be a functor.

In the case of JavaScript, filter is a functor because it returns an Array, however forEach is not a functor because it returns undefined. ie. forEach does not maintain structure.

Functors come from category theory in mathematics, where functors are defined as "homomorphisms between categories". Let's draw some meaning out of those words.

homo = same morphisms = functions that maintain structure category = type According to the theory, function F is a functor when for two composable ordinary functions f and g

F(f . g) = F(f) . F(g) where . indicates composition. ie. functors must preserve composition.

So given this equation we can prove wether a given function is indeed a functor or not.

Array Functor We saw that map is a functor that acts on type Array. Let us prove that the JavaScript Array.map function is a functor.

function compose(f, g) {

   return function(x) {return f(g(x))}

} Composing functions is about calling a set of functions, by calling the next function, with results of the previous function. Note that our compose function above works from right to left. g is called first then f.

[1, 2, 3].map(compose(plus1, plus2)) ==>> [ 4, 5, 6 ]

[1, 2, 3].map(plus2).map(plus1) ==>> [ 4, 5, 6 ] Yes! map is indeed a functor.

Lets try some functors. You can write functors for values of any type, as long as you can unwrap the value and return a structure.

String Functor So can we write a functor for type string? Can you unwrap a string? Actually you can, if you think of a string as an array of chars. So it is really about how you look at the value. We also know that chars have char codes which are integers. So we run plus1 on every char charcode, wrap them back to a string and return it.

function stringFunctor(value, fn) {

   var chars = value.split("")  
   return chars.map(function(char) {  
       return String.fromCharCode(fn(char.charCodeAt(0)))  
   }).join("")  

}

stringFunctor("ABCD", plus1) ==>> "BCDE" You can begin to see how awesome functors are. You can actually write a parser using the string functor as the basis.

Function Functor In JavaScript functions are first class citizens. That means you can treat functions like any other value. So can we write a functor for value of type function? We should be able to! But how do we unwrap a function? You can unwrap a function by calling it and getting its return value. But we straight away run into a problem. To call the function we need its arguments. Remember that the functor only has the function that came in as the value. We can solve this by having the functor return a new function. This function is called with the arguments, and we will in turn call the value function with the argument, and call the original functors function with the value returned!

function functionFunctor(value, fn) {

   return function(initial) {  
       return function() {  
           return fn(value(initial))  
       }  
   }  

}

var init = functionFunctor(function(x) {return x * x}, plus1) var final = init(2) final() ==> 5 Our function functor really does nothing much, to say the least. But there a couple things of note here. Nothing happens until you call final. Every thing is in a state of suspended animation until you call final. The function functor forms the basis for more awesome functional stuff like maintaining state, continuation calling and even promises. You can write your own function functors to do these things!

MayBe Functor function mayBe(value, fn) {

   return value === null || value === undefined ? value : fn(value)

} Yes, this is a valid functor.

mayBe(undefined, compose(plus1, plus2)) ==>> undefined mayBe(mayBe(undefined, plus2), plus1) ==>> undefined mayBe(1, compose(plus1, plus2)) ==>> 4 mayBe(mayBe(1, plus2), plus1) ==>> 4 So mayBe passes our functor test. There is no need for unrapping or wrapping here. It just returns nothing for nothing. Maybe is useful as a short circuiting function, which you can use as a substitute for code like

if (result === null) {

   return null

} else {

   doSomething(result)

} Identity Function function id(x) {

   return x

} The function above is known as the identity function. It is just a function that returns the value passed to it. It is called so, because it is the identity in composition of functions in mathematics.

We learned earlier that functors must preserve composition. However something I did not mention then, is that functors must also preserve identity. ie.

F(value, id) = value Lets try this for map.

[1, 2, 3].map(id) ==>> [ 1, 2, 3 ] Type Signature The type signature of a function is the type of its argument and return value. So the type signature of our plus1 function is

f: int -> int The type signature of the functor map depends on the type signature of the function argument. So if map is called with plus1 then its type signature is

map: [int] -> [int] However the type signature of the given function need not be the same as above. We could have a function like

f: int -> string in which the type signature of map would be

map: [int] -> [string] The only restriction being that the type change does not affect the composability of the functor. So in general a functor's type signature can

F: A -> B In other words map can take an array of integers and return an array of strings and would still be a functor.

Monads are a special case of Functors whos type signature is

M: A -> A