What is Gzip and JavaScript compression at all:
http://wrzasq.pl/blog/serving-static-content-css-and-javascript-with-gzip.html
http://betterexplained.com/articles/how-to-optimize-your-site-with-gzip-compression/
http://stackoverflow.com/questions/16883241/how-to-host-static-content-pre-compressed-in-apache
https://gtmetrix.com/enable-gzip-compression.html
Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts
Monday, June 13, 2016
Friday, June 10, 2016
WEBPACK - what is it Hot Module Reload, flags, process.env etc
Here is a good explanation what is Hot Module Reload:
http://matthewlehner.net/react-hot-module-replacement-with-webpack/
If you’re interested in a more in depth explanation of how it works, check out the answer to What exactly is Hot Module Replacement in Webpack on Stackoverflow.
http://webpack.github.io/docs/hot-module-replacement-with-webpack.html
http://stackoverflow.com/questions/24581873/what-exactly-is-hot-module-replacement-in-webpack#answer-24587740
http://matthewlehner.net/react-hot-module-replacement-with-webpack/
If you’re interested in a more in depth explanation of how it works, check out the answer to What exactly is Hot Module Replacement in Webpack on Stackoverflow.
http://webpack.github.io/docs/hot-module-replacement-with-webpack.html
http://stackoverflow.com/questions/24581873/what-exactly-is-hot-module-replacement-in-webpack#answer-24587740
webpack-dev-server --progress --inline
--progressdisplays the compilation progress when building--inlineadds webpacks automatic refresh code inline with the compile application
--profile
--colors
--watch
--display-error-details
--display-cached
--content-base /src
Profiling
If you wish to have a more in-depth idea of what is taking how long, you can use the --profile switch. This will cause WebPack to display more detailed timing informations. Combine this with the switches above to get a very detailed message and information set, which will contain the timings of your modules.
The timing "keys"
factory: The time it took to build the module information.
building: The time that was spent building the module (loaders, for example).
dependencies: The time that was spent gathering and connecting the dependencies
Process.env:
Webpack configuration can be a CommonJS module and can pick up on environment variables via Node's process.env object.
AMD
https://webpack.github.io/docs/amd.html
Wednesday, April 13, 2016
JAVASCRIPT - visualization of Bitcoins transactions by JS frameworks
Post in Twitter about the matter: https://twitter.com/pluralsight/status/719978158963978240
Example of JS visualization of Bitcoin transactions: http://bitbonkers.com/
JS framework Three JS: http://threejs.org/
JS framework Oimo JS: http://lo-th.github.io/Oimo.js/
Live stream of Bitcoins transactions: https://blockchain.info/
Example of JS visualization of Bitcoin transactions: http://bitbonkers.com/
JS framework Three JS: http://threejs.org/
JS framework Oimo JS: http://lo-th.github.io/Oimo.js/
Live stream of Bitcoins transactions: https://blockchain.info/
Thursday, April 7, 2016
JAVASCRIPT - difference between call and apply functions
CALL
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Function/call
APPLY
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
Its functions almost similar.
Its fundamental difference is that call() receive in its parameters a LIST of arguments, but apply() - single array of arguments.
Примечание: хотя синтаксис этой функции практически полностью идентичен функции
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Function/call
APPLY
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
Its functions almost similar.
Its fundamental difference is that call() receive in its parameters a LIST of arguments, but apply() - single array of arguments.
Примечание: хотя синтаксис этой функции практически полностью идентичен функции
apply(), фундаментальное различие между ними заключается в том, что функция call() принимает список аргументов, в то время, как функция apply() - одиночный массив аргументов.
JAVASCRIPT - the use of bind method of Function.prototype.bind()
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
Method bind() will bind the scope of the object's (passed as parameter) this to the function on which it was called.
Method bind() will bind the scope of the object's (passed as parameter) this to the function on which it was called.
this.x = 9;
var module = {
x: 81,
getX: function() { return this.x; }
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9, поскольку в этом случае this ссылается на глобальный объект
// создаём новую функцию с this, привязанным к module
var boundGetX = getX.bind(module);
boundGetX(); // 81
function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
// Создаём функцию с предустановленным ведущим аргументом
var leadingThirtysevenList = list.bind(undefined, 37);
var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
Wednesday, March 30, 2016
JavaScript - on the way to control hardware
Thus this sounds like a joke, JavaScript language is aiming to control hardware in the future:
https://tessel.io/
http://www.espruino.com/
https://tessel.io/
http://www.espruino.com/
Wednesday, February 24, 2016
Monday, February 8, 2016
WEB AUDIO - short example of WEB Audio API use (link)
http://gonehybrid.com/how-to-add-sound-effects-to-your-ionic-app-with-native-audio/
https://www.airpair.com/ionic-framework/posts/using-web-audio-api-for-precision-audio-in-ionic
Io.sound (a plugin based on WEB Audio API) - a good examples of its use:
http://ionden.com/a/plugins/ion.sound/en.html
https://blog.nraboy.com/2014/11/playing-audio-android-ios-ionicframework-app/
http://stackoverflow.com/questions/32507229/saving-web-audio-api-output-to-local-file-in-ionic
https://www.airpair.com/ionic-framework/posts/using-web-audio-api-for-precision-audio-in-ionic
Io.sound (a plugin based on WEB Audio API) - a good examples of its use:
http://ionden.com/a/plugins/ion.sound/en.html
https://blog.nraboy.com/2014/11/playing-audio-android-ios-ionicframework-app/
http://stackoverflow.com/questions/32507229/saving-web-audio-api-output-to-local-file-in-ionic
Friday, February 5, 2016
Friday, January 29, 2016
JAVASCRIPT vs ANGULARJS - copy object by value, not by reference
In JavaScript copy of object is done by reference:
var newObj = Object.create(oldObj); //Modification in newObj would be reflected in oldObj.
JavaScript solution 1: Inline deep copying (if you know its structure)
var newObj = {
name: source.name,
type: source.type
}
JavaScript solution 2: Use JSON parse (it could be more slower)
var newObject = JSON.parse(JSON.stringify(oldObject));
Angular way:
var newObject = angular.copy(oldObject);
var newObj = Object.create(oldObj); //Modification in newObj would be reflected in oldObj.
JavaScript solution 1: Inline deep copying (if you know its structure)
var newObj = {
name: source.name,
type: source.type
}
JavaScript solution 2: Use JSON parse (it could be more slower)
var newObject = JSON.parse(JSON.stringify(oldObject));
Angular way:
var newObject = angular.copy(oldObject);
JAVASCRIPT - JavaScript the Good Parts by Douglas Crockford (my notes)
EQUALS = = =
Always use = = = ,never = =
SCOPE
JavaScript has function scope, not block scope. The use of 'var' keyword could be confusing in it.
Declare all variables at the top of the function.
GLOBAL VARIABLES
Global variables are evil.
Avoid global variables.
When using it, be explicit and use UPPER_CASE
var a = b = 0 // it is confusing
It does not means var a = 0, var b = 0
It means you've created local a and global b:
b = 0;
var a = b;
INCREMENTATION Use x += 1 instead of x++
BRACKETS
Always put curly brackets on the right of statement etc.
e.g.
return { //OK
};
return
{ //syntactic error in JS
};
Always put the curly braces on!
if (a) (b); (c); // Creates confusion
if (a) { (b); (c); } //result 1 OK
if (a) { (b) }; (c); //result 2 OK
NEW
Don't use the 'new' keyword for an object creation.
FOR
In 'for' loop over the objects properties you need to check that this property is the one that belongs to the the object and not to its prototype:
for (name in object) {
if (object.hasOwnProperty(name)) {
...
}
}
But... the 'hasOwnProperty' is not the statement, but function, so it needs to have an extra safe call on prototype. This is HORRIBLE, but it is the most reliable way do it:
for (name in object) {
if (Object.prototype.hasOwnProperty.call(object, name)) {
...
}
}
ARRAYS
Use splice instead of delete if you need to remove from an array.
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1]; //['a', undefined, 'c', 'd']
myArray.splice(1, 1); //['a', 'c', 'd']
myArray.splice(1, 1); //start from index 1 and delete 1 element
Splice will be slow because it will move each element in order to fill an empty place...
ARRAYS vs OBJECTS
Use objects when the names are arbitrary strings
Use arrays when the names are sequential integers
NULL and UNDEFINED
All values are objects except null and undefined.
Don't store undefined in the object, it's confusing (like is it was declared and not defined?)
TYPEOF
array and null are 'object'
Use Arraye.isArray([]); //true
FALSY VALUES
false
null
undefined
"" (empty string)
0
NaN
REFERENCE
Objects are passed by reference, not by value
The = = = compares object refs, not values!!!
STRINGS to NUMBERS
+"42" = = = 42
Number("42") = = = 42
parseInt("42", 10) = = = 42
+"3" + (+"4") = = = 7
&&
if (a) {
return a.member;
} else {
return a;
}
It is the same as:
return a && a.member
SWITCH
Switch value can be a string
Case values can be expressions
FUNCTION
Function statement (or declaration) - if the first token in a statement is function, then it is a function statement.
function foo() {}
expands to:
var foo = function foo() {};
which fother expands to:
var foo = undefinded; //it was hoisted
foo = function foo() {};
RETURN
Return statement - if there is no expression, then the retrun value is undefined
PARAMETERS
Pseudo parameters - each function receives are arguments ans this there is no expression.
Arguments - an array like object (it is not an array) of all parameters that were passed to the function.
arguments.length // is a number of all arguments
Extra arguments ignored, Missed arguments will be undefined.
4 ways to call a function:
Function form (bound to the global object, fixed in ES5/strict, in ES6 to undefined)
functionObject(args)
Method form (bound to this of object)
thisObject.methodName(args)
thisObject["methodName"] (args)
Constructor form
new FunctionObject(args)
Apply form
functionObject.apply(thisObject, [args])
An inner function does not get access to the outer this. Work around:
var that = this; //this allows to inner function get reference to outer this of the function
Always use = = = ,never = =
SCOPE
JavaScript has function scope, not block scope. The use of 'var' keyword could be confusing in it.
Declare all variables at the top of the function.
GLOBAL VARIABLES
Global variables are evil.
Avoid global variables.
When using it, be explicit and use UPPER_CASE
var a = b = 0 // it is confusing
It does not means var a = 0, var b = 0
It means you've created local a and global b:
b = 0;
var a = b;
INCREMENTATION Use x += 1 instead of x++
BRACKETS
Always put curly brackets on the right of statement etc.
e.g.
return { //OK
};
return
{ //syntactic error in JS
};
Always put the curly braces on!
if (a) (b); (c); // Creates confusion
if (a) { (b); (c); } //result 1 OK
if (a) { (b) }; (c); //result 2 OK
"Premature optimization is the root of all evil"Donald KnuthOnly optimize the code that is taking a lot of the time.
NEW
Don't use the 'new' keyword for an object creation.
FOR
In 'for' loop over the objects properties you need to check that this property is the one that belongs to the the object and not to its prototype:
for (name in object) {
if (object.hasOwnProperty(name)) {
...
}
}
But... the 'hasOwnProperty' is not the statement, but function, so it needs to have an extra safe call on prototype. This is HORRIBLE, but it is the most reliable way do it:
for (name in object) {
if (Object.prototype.hasOwnProperty.call(object, name)) {
...
}
}
ARRAYS
Use splice instead of delete if you need to remove from an array.
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1]; //['a', undefined, 'c', 'd']
myArray.splice(1, 1); //['a', 'c', 'd']
myArray.splice(1, 1); //start from index 1 and delete 1 element
Splice will be slow because it will move each element in order to fill an empty place...
ARRAYS vs OBJECTS
Use objects when the names are arbitrary strings
Use arrays when the names are sequential integers
NULL and UNDEFINED
All values are objects except null and undefined.
Don't store undefined in the object, it's confusing (like is it was declared and not defined?)
TYPEOF
array and null are 'object'
Use Arraye.isArray([]); //true
FALSY VALUES
false
null
undefined
"" (empty string)
0
NaN
REFERENCE
Objects are passed by reference, not by value
The = = = compares object refs, not values!!!
STRINGS to NUMBERS
+"42" = = = 42
Number("42") = = = 42
parseInt("42", 10) = = = 42
+"3" + (+"4") = = = 7
&&
if (a) {
return a.member;
} else {
return a;
}
It is the same as:
return a && a.member
SWITCH
Switch value can be a string
Case values can be expressions
FUNCTION
Function statement (or declaration) - if the first token in a statement is function, then it is a function statement.
function foo() {}
expands to:
var foo = function foo() {};
which fother expands to:
var foo = undefinded; //it was hoisted
foo = function foo() {};
RETURN
Return statement - if there is no expression, then the retrun value is undefined
PARAMETERS
Pseudo parameters - each function receives are arguments ans this there is no expression.
Arguments - an array like object (it is not an array) of all parameters that were passed to the function.
arguments.length // is a number of all arguments
Extra arguments ignored, Missed arguments will be undefined.
4 ways to call a function:
Function form (bound to the global object, fixed in ES5/strict, in ES6 to undefined)
functionObject(args)
Method form (bound to this of object)
thisObject.methodName(args)
thisObject["methodName"] (args)
Constructor form
new FunctionObject(args)
Apply form
functionObject.apply(thisObject, [args])
An inner function does not get access to the outer this. Work around:
var that = this; //this allows to inner function get reference to outer this of the function
function factorial(n) { return (function foo(result) { //result is the 1 passed in IIFE parameter while (n > 1) { //IIFE copy n value and operates with it on its own scope result *= n; n -= 1; } return result; })(1); }CLOSUREContext of an inner function includes the scope of the outer function.An inner function enjoys that context even after the parent functions have returned.var digit_name = (function () { var names = ['zero', 'one', 'two', 'three']; //dies immediately after execution return function (n) { //closure remains as a digit_name return names[n]; }; })();digit_name here would be equal of IIFE return function:function (n) { //it is a closure, that remember array names[] of outer IIFE scope return names[n]; };There is mistake on definition on the image above:In fact, outer function here is outer() and it cannot see y of inner function inner().Inner function inner() can see the both a and y.MONADS (macroid)function MONAD() {return function unit(value) {var monad = Object.create(null);monad.bind = function (func) {return func(value);};return monad;}}var unit = MONAD();var monad = unit("Hello World!");monad.bind(alert);Improving Monads:Now you can call alert method by two different ways:monad.bind(alert);monad.alert();Usually ajax() method takes remote data and use it in some function like this:$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
});
Maybe MonadsOne of the use is check for NPE:TURN BASED PROCESSING INSTEAD OF THREADSNever wait, never block, finish fastThreads causes races, Mutual Exclusion causes dead locksPROMISE: Promise MonadsPromise is event generator.In this example the use of failure is the better way to handle errors then throwing exceptions on try/catch block, cause it keeps stack full. my_promise.when(a).when(b).when(c, failure)https://github.com/douglascrockford/monadIdentity Monad// var identity = MONAD(); // var monad = identity("Hello world."); // monad.bind(alert);Ajax Monad// var ajax = MONAD() // .lift('alert', alert); // var monad = ajax("Hello world."); // monad.alert();Maybe Monad// var maybe = MONAD(function (monad, value) { // if (value === null || value === undefined) { // monad.is_null = true; // monad.bind = function () { // return monad; // }; // return null; // } // return value; // }); // var monad = maybe(null); // monad.bind(alert); // Nothing happens.VIDEO TO WATCH:Carl Hewitt. The Actor Model (everything you wanted to know, but were afraid to ask )Mark Miller (authore of Promise model). Secure Distributed Programming with Object-capabilities in JavaScriptTypeScriptTypeScript was developed by Microsoft to make Visual Studio work better with JavaScript. )))TypeScript generates very good quality JavaScript code (many other transpilers dont)Typed JS like TypeScript does not decrease the amount of tests you need to write to be sure there is no errors connected with types. So it is almost vain trade-off.It is not a Typesystem it is annoying.Lisp developed the most difficult system without of types...His JSLint will not work with TypeScript
JAVASCRIPT - the use of double and triple equals "===" vs "=="
The rule for use of triple an double equals in JavaScript is simple:
Always use = = = and never = =
(Always use triple equals and
never double equals)
Thursday, January 28, 2016
JAVASCRIPT - Oracle JET JavaScript framework
Saturday, January 23, 2016
Advance JavaScript by Kyle Simpson (my notes)
Kyle Simpson
https://www.patreon.com/getify?ty=h
https://developer.mozilla.org/en-US/docs/Web/JavaScript
http://www.ecma-international.org/ecma-262/6.0/index.html
https://github.com/rwaldron/idiomatic.js
https://en.wikipedia.org/wiki/Just-in-time_compilation
JIT compilation - just-in-time (JIT) compilation, also known as dynamic translation, is compilation done during execution of a program – at run time – rather than prior to execution.
Compiler terminology:
LHS - left hand side for an assignment
RHS - right hand side for an assignment
var foo = 'bar'
var foo here is LHS reference an it is TARGET
'bar' is RHS reference and it is a SOURCE
Scope
function baz(foo) {
foo = 'bam';
bam = 'yay'
}
foo here would be the local scope variable created in compile time
bam in NO STRICT mode will be created as a global variable during run time, cause in local scope it will not be founded.
bam in STRICT mode will produce error because bam never was created either in local or global scope.
This happen because declaration in JS goes only with VAR or FUNCTION words.
Undeclared variable means we unable to find proper LHS reference in any of the scopes that we have access to.
In JS undeclared and undefined are totally different words.
Undefined variable - variable that was declared, but has special empty value that was mistakenly named in JS as undefined (should be named with better word).
Undefined is an actual real value for empty value, it is a type. (e.g. there cannot be a vacuum where value exist)
bar(); it is RHS because... it is not LHS :) (it has not '=' sign)
function baz(foo) {
var foo = 'bam';
bam = 'yay'
finction bam() {
var baz = 'bla';
}
bam();
}
bam(); if this function would be called from global scope it will produce reference error.
FUN http://my-fly.ru/blog/43082783722/Retsept-schastlivoy-zhizni-po-odesski
There could be only two cases:
OR Function Declaration: (if the 'function' word is the the very first word in the statement)
function bar() {
}
OR Function Expression: (the 'function' word is NOT the first word in the statement)
var bla = function bar() {
}
bar(); //will result in ERROR if it is called outside of local scope
ALWAYS use Named Function Expression instead of Anonymous.
It results in 3 advantages:
- it gives self reference inside the local scope
- it allows debugging the function
- its name gives description for what it is doing
EVAL keyword is a way of cheating compiler, making it think that parameter of eval was created before. For instance:
var bar = 'bar';
function foo(str) {
eval(str); //cheating
console.log(bar); //it will print 42, not 'bar'
}
foo('var bar = 42;');
NEVER use 'eval' as well as 'with' statement (even if the strict mode does create for it new scope)
I I F E pattern
The IIFE term was invented by Ben Alman ('Cowboy') http://benalman.com/
IIFE sometimes rendered as “self-executing anonymous function” (or self-invoked anonymous function)
I I F E - Immediately Invoked Function Expression
CLOSURE (First-class functions)
Closure is when a function 'remembers' and access its lexical scope even when the function is executed outside that lexical scope.
http://skilldrick.co.uk/2011/04/closures-explained-with-javascript/
https://en.wikipedia.org/wiki/Closure_%28computer_programming%29
https://en.wikipedia.org/wiki/First-class_citizen
SCOPE
Lexical scope - has author scope (JavaScript)
Dynamic scope - has run time (Bash)
Scope can be created by:
- Functions
- Curly braces and keyword let
- Try and catch block
Cheating scope by eval and with keywords.
HOISTING
It is invented terme to explain how JS works.
Function hoisted first, before variables.
Keyword let is not hoisted.
THIS
Every function, while executing, has a reference to its current execution context, called THIS
4 Binding Rules of THIS by order. Rules of precedence by Call Side:
- Default binding rule:
In strict mode of current function this = Undefined value, else = global object
- Implicit binding rule:
function foo() { console.log(this.bar) }
var bar = 'bar';
var o2 = { bar: 'bar2', foo: foo};
foo(); //bar
o2.foo(); //bar2 it is implicit binding
- Explicit binding rule: use of call or apply in call side with object in its parameter.
bar.call(obj) - use this of passed in param obj.
Hard explicit binding is encapsulate bar.call(obj) in IIFE
- By NEW binding
- Create new object
- Link this new object with other object
- New object bound to THIS for the purposes of the function call
- Implicitly insert at the end of function return this; if no other return is provided.
Classic Module Pattern
- It must be executed in the outer wrapper function (not necessary IIFE)
- One or more function that get returned from that function call
Principle of Least Privilege, or Least Exposure (make everything private and only expouse what needs to be public e.g. executing foo.bar(); // bar)
The object of return is public API of module. Inside is its private encapsulated data.
var foo = (function () {
var o = { bar: 'bar' };
return {
bar: function() {
console.log(o.bar);
}
}
})();
foo.bar(); //bar
Modified Module Pattern (much more organized)
It is better use object variable instead of anonymous function. It can be updated in run time.
var foo = (function () {
var publicAPI = {
bar: function() {
publicAPI.baz();
},
baz: function() {
console.log('baz');
}
}
return publicAPI;
})();
foo.bar(); //baz
Module Pattern in ES6
It is better use object variable instead of anonymous function. It can be updated in run time.
E.g. module goes in separate foo.js file:
var o = { bar: 'bar' };
export function bar() {
return o.bar;
}
From other test.js file:
import bar from 'foo'; //will import just one function from that module
bar(); //bar
module foo from 'foo';
foo.bar(); //bar
Object Orienting
A constructor makes an object linked to (not to be 'based on') its own prototype.
PROTOTYPE
__proto__ is a public link to the internal property of [[ prototype ]] . It is pronounced as kind of 'donedoproto', It was invented by Mozilla and supported for all other browsers except... IE till the version 11 (Edge).
__proto__ became standard only since ES6.
[[ prototype ]] . Is a linkage from one object to another.
var a1 = new Foo('a1');
a1.__proto__ //even in IE
a1.__proto__ === Object.getPrototypeOf(a1); //prior to IE 11
a1.__proto__ === a1.constructor.prototype; //always available, but it is writable function
Using polymorphism avoid shadowing of properties names of object and its prototype.
Objects Linked
function Foo(who) {
this.me = who;
}
function Bar(who) {
Foo.call(this, who); //way 1
}
Bar.prototype = Object.create(Foo.prototype); //way 2
Inheritance vs. Behavior delegation
var a1 = new Foo();
Foo.prototype.speak = function....
a1.speak() //this is Behavior delegation from object to its prototype (it is not by copying)
OLOO pattern
Object Linked Other Object
Async callbacks
Generators in ES6
It is a new kind of function: function*
It can stop on keyword yield
It can return kind of iterator
yield null - its a kind of way to send messages to the generator.
Its a two way passing messages mechanism.
It should eliminate Promises and callbacks.
https://www.patreon.com/getify?ty=h
https://developer.mozilla.org/en-US/docs/Web/JavaScript
http://www.ecma-international.org/ecma-262/6.0/index.html
https://github.com/rwaldron/idiomatic.js
https://en.wikipedia.org/wiki/Just-in-time_compilation
JIT compilation - just-in-time (JIT) compilation, also known as dynamic translation, is compilation done during execution of a program – at run time – rather than prior to execution.
Compiler terminology:
LHS - left hand side for an assignment
RHS - right hand side for an assignment
var foo = 'bar'
var foo here is LHS reference an it is TARGET
'bar' is RHS reference and it is a SOURCE
Scope
function baz(foo) {
foo = 'bam';
bam = 'yay'
}
foo here would be the local scope variable created in compile time
bam in NO STRICT mode will be created as a global variable during run time, cause in local scope it will not be founded.
bam in STRICT mode will produce error because bam never was created either in local or global scope.
This happen because declaration in JS goes only with VAR or FUNCTION words.
Undeclared variable means we unable to find proper LHS reference in any of the scopes that we have access to.
In JS undeclared and undefined are totally different words.
Undefined variable - variable that was declared, but has special empty value that was mistakenly named in JS as undefined (should be named with better word).
Undefined is an actual real value for empty value, it is a type. (e.g. there cannot be a vacuum where value exist)
bar(); it is RHS because... it is not LHS :) (it has not '=' sign)
function baz(foo) {
var foo = 'bam';
bam = 'yay'
finction bam() {
var baz = 'bla';
}
bam();
}
bam(); if this function would be called from global scope it will produce reference error.
FUN http://my-fly.ru/blog/43082783722/Retsept-schastlivoy-zhizni-po-odesski
There could be only two cases:
OR Function Declaration: (if the 'function' word is the the very first word in the statement)
function bar() {
}
OR Function Expression: (the 'function' word is NOT the first word in the statement)
var bla = function bar() {
}
bar(); //will result in ERROR if it is called outside of local scope
ALWAYS use Named Function Expression instead of Anonymous.
It results in 3 advantages:
- it gives self reference inside the local scope
- it allows debugging the function
- its name gives description for what it is doing
EVAL keyword is a way of cheating compiler, making it think that parameter of eval was created before. For instance:
var bar = 'bar';
function foo(str) {
eval(str); //cheating
console.log(bar); //it will print 42, not 'bar'
}
foo('var bar = 42;');
NEVER use 'eval' as well as 'with' statement (even if the strict mode does create for it new scope)
I I F E pattern
The IIFE term was invented by Ben Alman ('Cowboy') http://benalman.com/
IIFE sometimes rendered as “self-executing anonymous function” (or self-invoked anonymous function)
I I F E - Immediately Invoked Function Expression
The most widely accepted way to tell the parser to expect a function expression is just to wrap it in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters thefunctionkeyword, it knows to parse it as a function expression and not a function declaration.
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
CLOSURE (First-class functions)
Closure is when a function 'remembers' and access its lexical scope even when the function is executed outside that lexical scope.
http://skilldrick.co.uk/2011/04/closures-explained-with-javascript/
https://en.wikipedia.org/wiki/Closure_%28computer_programming%29
https://en.wikipedia.org/wiki/First-class_citizen
Any function defined inside another function can access the outer function’s passed-in arguments and variables (this relationship is known as a closure)
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
A closure is a function called in one context that remembers variables defined in another context – the context in which it was defined.
http://skilldrick.co.uk/2011/04/closures-explained-with-javascript/
SCOPE
Lexical scope - has author scope (JavaScript)
Dynamic scope - has run time (Bash)
Scope can be created by:
- Functions
- Curly braces and keyword let
- Try and catch block
Cheating scope by eval and with keywords.
HOISTING
It is invented terme to explain how JS works.
Function hoisted first, before variables.
Keyword let is not hoisted.
THIS
Every function, while executing, has a reference to its current execution context, called THIS
4 Binding Rules of THIS by order. Rules of precedence by Call Side:
- Default binding rule:
In strict mode of current function this = Undefined value, else = global object
- Implicit binding rule:
function foo() { console.log(this.bar) }
var bar = 'bar';
var o2 = { bar: 'bar2', foo: foo};
foo(); //bar
o2.foo(); //bar2 it is implicit binding
- Explicit binding rule: use of call or apply in call side with object in its parameter.
bar.call(obj) - use this of passed in param obj.
Hard explicit binding is encapsulate bar.call(obj) in IIFE
- By NEW binding
- Create new object
- Link this new object with other object
- New object bound to THIS for the purposes of the function call
- Implicitly insert at the end of function return this; if no other return is provided.
Classic Module Pattern
- It must be executed in the outer wrapper function (not necessary IIFE)
- One or more function that get returned from that function call
Principle of Least Privilege, or Least Exposure (make everything private and only expouse what needs to be public e.g. executing foo.bar(); // bar)
The object of return is public API of module. Inside is its private encapsulated data.
var foo = (function () {
var o = { bar: 'bar' };
return {
bar: function() {
console.log(o.bar);
}
}
})();
foo.bar(); //bar
Modified Module Pattern (much more organized)
It is better use object variable instead of anonymous function. It can be updated in run time.
var foo = (function () {
var publicAPI = {
bar: function() {
publicAPI.baz();
},
baz: function() {
console.log('baz');
}
}
return publicAPI;
})();
foo.bar(); //baz
Module Pattern in ES6
It is better use object variable instead of anonymous function. It can be updated in run time.
E.g. module goes in separate foo.js file:
var o = { bar: 'bar' };
export function bar() {
return o.bar;
}
From other test.js file:
import bar from 'foo'; //will import just one function from that module
bar(); //bar
module foo from 'foo';
foo.bar(); //bar
Object Orienting
A constructor makes an object linked to (not to be 'based on') its own prototype.
PROTOTYPE
__proto__ is a public link to the internal property of [[ prototype ]] . It is pronounced as kind of 'donedoproto', It was invented by Mozilla and supported for all other browsers except... IE till the version 11 (Edge).
__proto__ became standard only since ES6.
[[ prototype ]] . Is a linkage from one object to another.
var a1 = new Foo('a1');
a1.__proto__ //even in IE
a1.__proto__ === Object.getPrototypeOf(a1); //prior to IE 11
a1.__proto__ === a1.constructor.prototype; //always available, but it is writable function
Using polymorphism avoid shadowing of properties names of object and its prototype.
Objects Linked
function Foo(who) {
this.me = who;
}
function Bar(who) {
Foo.call(this, who); //way 1
}
Bar.prototype = Object.create(Foo.prototype); //way 2
Inheritance vs. Behavior delegation
var a1 = new Foo();
Foo.prototype.speak = function....
a1.speak() //this is Behavior delegation from object to its prototype (it is not by copying)
OLOO pattern
Object Linked Other Object
Async callbacks
Generators in ES6
It is a new kind of function: function*
It can stop on keyword yield
It can return kind of iterator
yield null - its a kind of way to send messages to the generator.
Its a two way passing messages mechanism.
It should eliminate Promises and callbacks.
This example shows how generators could work asynchronous way,
even if it looks like synchronous.
Combination of Generators and Promises is the future!
No Threads just Shared Memory with Events Loop
Subscribe to:
Posts (Atom)











