Last active
January 23, 2016 12:33
-
-
Save wb4r/41674e85e5e688151f6a to your computer and use it in GitHub Desktop.
Notes and Shortcuts to JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
::::::::::::::::::::::::::::::::::::::::::::: | |
::::::::::::::::::: INDEX ::::::::::::::::::: | |
::::::::::::::::::::::::::::::::::::::::::::: | |
1- PRIMITIVES VS. OBJECTS | |
2- NULL VS. UNDEFINED | |
3- FUNCTION DECLARATION AND FUNCTION EXPRESSION | |
4- JS FUNCTION-S: FIRST CLASS VALUES | |
5- ANONYMOUS FUNCTIONS, SCOPE AND CLOSURE | |
6- FUNCTION EXPRESSION WITH GROUPING OPERATORS | |
7- NAMED FUNCTION EXPRESSIONS | |
8- IMMEDIATELY-INVOKED FUNCTION EXPRESSIONS | |
9- TYPES OF FUNCTIONS SUMMARY | |
10- OBJECT LITERAL | |
11- OBJECT CONSTRUCTOR | |
12- INSTANCEOF AND MODIFYING OBJECTS | |
13- CLASSICAL OOP VS. PROTOTYPAL INHERITANCE | |
14- PROTOTYPES THEORY | |
15- PROTOTYPES CODED | |
16- PROTOTYPE CHAIN | |
17- CALL FUNCTION | |
18- HANDLEBARS | |
19- LOOPS AND STATEMENTS | |
20- CLASS and SUBCLASS | |
21- SECURE VALUES | |
22- 'SECURE' OBJECTS PROPERTIES BY CONVENTION | |
23- COPYING OBJECTS WITH jQUERY | |
//##########################################################################// | |
//##########################################################################// | |
//##########################################################################// | |
1- PRIMITIVES VS. OBJECTS | |
- There are 2 types in JS: Primitives and Objects. | |
- Primitives are numbers, strings, booleans, null and undefined. | |
- The rest is an Object. | |
2- NULL VS. UNDEFINED | |
- Undefined: variable, property or array item not initialized to a value. | |
- Null: means no object. | |
- NaN: is a number that cant be represented. | |
3- FUNCTION DECLARATION AND FUNCTION EXPRESSION | |
Function Declaration: | |
- Are handled before the code is evaluated. | |
- When evaluated, it creates a function and a variable with the same name. | |
- Stores the function Reference in the variable. | |
- A function Reference is a value that referes to a function. | |
- Must have names (identifier) | |
- 'Cannot' be declared inside if statements | |
function foo(bar) { | |
console.log(bar); | |
} | |
- Both this two get executed exactly, no matter when its called: | |
A(); | |
function A() { console.log("foo"); } | |
///// | |
function A() { console.log("foo"); } | |
A(); | |
Function Expression: | |
- The function is created as the code executes, at runtime. | |
- A function Reference is a value that referes to a function. | |
- The coder decides what to do with the function Reference. | |
var foo = function(bar) { | |
console.log(bar); | |
} | |
Function Assignment: | |
- Both FD and FE can be assigned to a variable: | |
var myVar = foo; | |
myVar(bar); | |
4-JS FUNCTION-S: FIRST CLASS VALUES | |
FCV means that you can: | |
- Assign the value to a variable or store it in an Array or Object. | |
- Pass the value to a function. | |
- Return the value from a function. | |
- A function Reference is a FCV. | |
5- ANONYMOUS FUNCTIONS, SCOPE AND CLOSURE | |
Anonymous Function: | |
- Is a function expression that has no name | |
Example of Conversion: | |
function handler() {console.log("Loaded!");} | |
window.onload = handler; | |
--->--->--->--->--->--->--->--->--->--->---> | |
window.onload = function() {console.log("Loaded!");} | |
Scope: | |
- Functions are always evaluated in the same scoping environment in which they | |
were defined. | |
- Variables with number or string it is passed by value. It means that only the | |
value is passed not the actual variable, therefore they dont change if modified. | |
- Variables passing objects or arrays are passed by reference. It means that the | |
vars are simply pointing to where in memory these obj and arr are and they may be | |
modified in memory. | |
Free Variables: | |
- If a Variable in a function body isnt defined locally AND it isnt global | |
it is from a function its nested in and available in its environment. | |
Closure: | |
- Closures are a function along with a referencing environment. | |
- The Closure contains the actual environment, not a copy. | |
- Closures are often used to capture state or event handlers. | |
- A Closure results when we combine a function that has free variables with an | |
environment that provides variable bindings for all those free variables. | |
Example WITHOUT closure: | |
var count = 0; | |
function counter() { | |
count += 1; | |
return count; | |
} | |
Example WITH closure: | |
function makeCounter() { | |
var count = 0; | |
function counter() { | |
count += 1; | |
return count; | |
} | |
return counter(); | |
} | |
6- FUNCTION EXPRESSION WITH GROUPING OPERATORS | |
- Watch and try the difference; one doesnt work and the other two return | |
differently: | |
function(){console.log("foo");} // SyntaxError | |
(function(){console.log("foo");}) // Returns the above | |
//--> (function(){console.log("foo")}) | |
(function(){console.log("foo");})(); // foo | |
- The first one is a function declaration and they cannot be annonymous, they | |
must have a name or identifier. | |
- The second one is evaluated as a function expression thanks to the grouping | |
operators (parenthesis). | |
7- NAMED FUNCTION EXPRESSIONS | |
- They are only accessible from within the function: | |
var D = function foo(){ | |
console.log("bar"); | |
}; | |
D(); // bar | |
foo(); // ReferenceError | |
- They are good for recursion: | |
var countdown = function a(counter) { | |
if (counter > 0) { | |
console.log(counter); // optional, to see the countdown | |
return a(--counter) // or count--; return a(count); | |
} | |
console.log('End of recursive function countdown'); | |
} | |
countdown(5); | |
8- IMMEDIATELY-INVOKED FUNCTION EXPRESSIONS | |
// Function Declaration example | |
var D = function(){ | |
return "bar"; | |
}; | |
D(); // "bar" | |
D; // returns the function | |
//////////////////////////////////////////////////// | |
// Function Expression with Grouping Operators example | |
var D = (function(){ // note the extra parenthesis | |
return "bar"; | |
}); // note the extra parenthesis | |
D(); // "bar" | |
D; // returns the function | |
//////////////////////////////////////////////////// | |
// IIFE Example | |
var D = (function(){ | |
return "bar"; | |
})(); // note the extra parenthesis at the end | |
D(); // TypeError | |
D; // "bar" | |
- Why is it called Immediately-invoked? Previously we have used it assigning it | |
to a variable, but it can be used as itslef, and it executes the same: | |
(function() { | |
return "bar" | |
})() | |
// no need for invoking, it returns "bar" | |
- So instead of an anonymous function in the global scope (or wherever it is | |
defined) we now have an UNNAMED Function Expression (or a self-executed FEwGO) | |
- Uses: | |
-> Avoid polluting the Global scope (used by JS libraries and plugins) | |
-> | |
9- TYPES OF FUNCTIONS SUMMARY | |
function A(){}; // Function declaration | |
var B = function(){}; // Function expression | |
var C = (function(){}); // Function expression with grouping operators | |
var D = function foo(){}; // Named function expression | |
var E = (function(){ // Immediately-invoked function expression (IIFE) | |
return function(){} // that returns a function | |
})(); | |
function(){} // Anonymous function (function expression) | |
10- OBJECT LITERAL | |
- Works well when its needed to create a small nr of objects | |
var taxi = { | |
make: "Nissan", | |
model: "Patrol", | |
year: 1995, | |
sell: function() {this.sold = true;} | |
}; | |
var dog = { | |
name: "Fido", | |
breed: "Mixed", | |
weight: 38, | |
bark: function() {console.log("Woof!");} | |
} | |
11- OBJECT CONSTRUCTOR | |
- Is similar to a function that returns an object. | |
- Its defined once and invoked to create a new object. | |
- By convention it is capitalized | |
- Works well when its needed to create many similar objects | |
function Dog(name, breed, weight) { | |
this.name = name; | |
this.breed = breed; | |
this.weight = weight; | |
this.bark = function() {console.log("Woof!");}; | |
} | |
var fido = new Dog("Fido", "Mixed", 38); | |
12- INSTANCEOF AND MODIFYING OBJECTS | |
console.log(fido instanceof Dog); // returns true | |
console.log(fido instanceof Car); // returns false | |
- Constructed objects can have their own independent properties after | |
creation: | |
fido.owner = "Bob"; | |
console.log(fido); | |
--> Dog {name: "Fido", breed: "Mixed", weight: 38, owner: "Bob"} | |
- Constructed objects can delete properties after creation: | |
delete fido.weight; | |
console.log(fido); | |
--> Dog {name: "Fido", breed: "Mixed", owner: "Bob"} | |
- Constructed objects can add new methods after creation as well: | |
fido.trust = function(person) { if (person) {return person} else {return false}}; | |
fido.trust(fido.owner); | |
13- CLASSICAL OOP VS. PROTOTYPAL INHERITANCE | |
- JS doesnt have classes. | |
- In JS objects inherit behavior from other objects. | |
- That is known as Prototypal Inheritance. | |
14- PROTOTYPES THEORY | |
- The objects we used to create with constructors use too much memory. | |
- Each of the instances has its own bark() method for example. | |
- Using prototypes we can create objects that are extensions of other | |
objects (of prototype objects). | |
- Objects can inherit properties and behavior from other objects called | |
prototypes. | |
- When a property or behavior isnt in the object itself, JS looks into its | |
parent, or prototype. | |
- Props and methods from the prototype can be overriden in the object. | |
- If we add a new property or method to the prototype after creating some | |
instances they will also inherit them automatically. | |
------------------------------------------------------------------------- | |
- Note: Functions in JS are Objects. | |
------------------------------------------------------------------------- | |
- We access the prototype with | |
Constructor.prototype | |
Dog.prototype | |
Car.prototype | |
- .prototype is a property of the Constructor, that is a function (and | |
an Object). | |
15- PROTOTYPES CODED | |
Basic structure of Constructor and Prototype: | |
// Dog Constructor | |
function Dog(name, breed, weight) { | |
this.name = name; | |
this.breed = breed; | |
this.weight = weight; | |
} | |
// Dog Prototype | |
Dog.prototype = { | |
species: "Canine", | |
bark: function() { | |
console.log("Woof!"); | |
}, | |
run: function() { | |
console.log("Run!"); | |
} | |
}; | |
// Or like this: | |
Dog.prototype.wag = function() { | |
console.log("Wag!"); | |
} | |
16- PROTOTYPE CHAIN | |
If we want a prototype different than the Dog.prototype but that it inherits | |
from the Dog Constructor we can just create one and chain it to the Consructor, | |
so ShowDog is still an instance of Dog: | |
function Dog(name, breed, weight) { | |
this.name = name; | |
this.breed = breed; | |
this.weight = weight; | |
} | |
function ShowDog(name, breed, weight, handler) { | |
// this.name = name; | |
// this.breed = breed; | |
// this.weight = weight; | |
this.handler = handler; | |
} | |
ShowDog.prototype = new Dog(); // if dont do that it wont recognize n,b,w | |
// but even recgonizing them it wont save them when creating a new ShowDog !! | |
// so or we declare them in ShowDog or we use .call | |
----------------------------- | |
var sd = new ShowDog("names", "breeds", 55, "me") | |
sd instanceof Dog --> true | |
sd instanceof ShowDog --> true | |
ShowDog instanceof Dog --> false | |
ShowDog.prototype instanceof Dog --> true | |
ShowDog.prototype.isPrototypeOf(sd) --> true | |
Dog.prototype.isPrototypeOf(sd) --> true | |
Prototypes are like CLASSES. You can create multiple classes, or just one, for | |
each constructor that is like the parent of the Prototypes. You want to put the | |
methods inside the Prototypes and not inside the Constructor, to avoid memory | |
issues. IF you create a prototype with a different name of the Constructor (showdog) | |
make sure to chain it to the constructor to inherit its properties. | |
17- CALL FUNCTION | |
Above, function Dog and ShowDog have some REPETITION. With CALL function we can | |
avoid this repetition. | |
function FunctionWeAreCalling(arg1, arg2, arg3) { | |
Constructor.call(this, arg1, arg2, arg3); | |
this.extraArg = parameters; | |
} | |
------------------------------------------------------------ | |
function ShowDog(name, breed, weight, handler) { | |
Dog.call(this, name, breed, weight); //equivalent to calling the | |
this.handler = handler; // function Dog(arg1,...) {} | |
} | |
The call method is a function that invokes the function and passes it the object | |
to use as this along with all the arguments for the Dog function. | |
With this code we are calling the Dog constructor function but telling it to use | |
our ShowDog instance as this, and so the Dog function will set the name, breed | |
and weight properties in our ShowDog object. | |
18- HANDLEBARS | |
::::Simple theory:::: | |
a- Create an empty <div> with an ID to store the dinamic data | |
b- Create an script inside the HTML for the handlebars code | |
c.1- When assigning what is going to be displayed put it in " " | |
c.2- Give it HTML code like "<p> content </p>" | |
c.3- Put the dinamic data between two handlebars like {{}} with what is going | |
to be a key of a future object. | |
d- Compile the handlebars with the variable where you assigned the HTML code (c.1) | |
~ = Handlebars.compile(varX) | |
e- Create an object referencing the variable of the function that was compiled. | |
The keys will be used in c.3 and its value is what will be displayed. | |
f- Make JS or jQuery modify the initial <div> content in a | |
document.getElementById("myData").innerHTML += data; | |
<div id="myData"></div> // a | |
<script type="text/javascript"> // b | |
// c | |
var myInfo = "<p>My name is {{name}} and I live in {{city}}"</p> | |
// d | |
var template = Handlebars.compile(myInfo); | |
// e | |
var data = template({ | |
name: "Willem", | |
city: "Edinburgh" | |
}); | |
// f | |
document.getElementById("myData").innerHTML += data; | |
</script> // end of b | |
::::Complex theory:::: | |
We use two <script>s: | |
- The first one will be the one displaying the content and will have a different | |
type= | |
- The second will have the engine of what will be displayed, like in the example | |
above. | |
- Also create an empty <div> with an ID to store the dinamic data | |
<div id="quoteData"></div> | |
First <script>: | |
a- Create a script with an ID and a type= different than "text/javascript" | |
b- Use the same technique of using {{}} for displaying dinamic content | |
c- Using a similar approach as Rails erb look at the following code: | |
c.1- The <ol> has no content for now and will be dinamically displayed. | |
c.2- 'each' will use an Array, called 'quotes', of Object s with key 'quote'. Each | |
of this 'quote' will be a future <li> | |
c.3- Inside the Handlebars, each is opened and closed with '#' and '/' respectively | |
// a | |
<script id="quote-template" type="text/x-handlebars-template"> | |
// b | |
<h3> Favorite {{name}} Quotes </h3> | |
// c.1 | |
<ol> | |
// c.2 | |
{{#each quotes}} // c.3 | |
<li>{{quote}} // c.2 | |
{{/each}} // c.3 | |
</ol> | |
</script> | |
Second <script>: | |
a- Create a script. This one doesnt need to have an ID or a different type= but | |
giving it an ID can be useful for later if you want to compile it outside your | |
HTML code. | |
b- Get the first <script> ID and assign it to a variable. | |
c- Compile the first script and assign it to a variable. This will be a function. | |
d- Create a variable referencing the variable of the function that was compiled. | |
d.1- As we said before, as the key for this object we will have an Array 'quotes:'. | |
d.2- This Array will content objects whose key will be each single 'quote:' and | |
its value will be the quote itself. | |
e- Make JS or jQuery modify the initial <div> content with the variable referencing | |
the compile XX | |
// a | |
<script type="text/javascript"> | |
// b | |
var quoteInfo = document.getElementById("quote-template").innerHTML; | |
// c | |
var template = Handlebars.compile(quoteInfo); | |
var data = template({ | |
name: "Victim of Hollywood", | |
// First script: c.2 | |
// Second script: d.1 | |
quotes: [ | |
// First script: c.2 | |
// Second script: d.2 | |
{quote: "I find your lack of faith disturbing"}, | |
{quote: "The Force is strong with this one"}, | |
{quote: "Luke, I am your father"} | |
] | |
}); | |
// e | |
document.getElementById("quoteData").innerHTML += data; | |
</script> | |
19- LOOPS AND STATEMENTS | |
FOR (ARRAY): | |
array = ["a", "b"] | |
for (var i = 0; i < array.length; i++) { | |
console.log(array[i]); | |
}; | |
// a | |
// b | |
FOR (OBJECT): | |
var data = { foo: 1, bar: 2 }; | |
for (var value in data) { | |
console.log(data[value]); | |
} | |
// 1 | |
// 2 | |
WHILE: | |
while (myVar > 0) { | |
}; | |
IF: | |
if (condition) { | |
} else if (condition) { | |
} else { | |
}; | |
Simple forEACH: | |
var arry = [1, 2, 3]; | |
arry.forEach(function(num) { | |
console.log(num); | |
}) | |
// 1 | |
// 2 | |
// 3 | |
Complex forEACH: | |
var arry = ["a", "b", "c"]; | |
arry.forEach(function(val, idx, arg) { | |
arg = "Free to play with arguments"; | |
console.log("Value: " + val + " - Index: " + idx + " - Arguments: " + arg) | |
}) | |
// Value: a - Index: 0 - Arguments: Free to play with arguments | |
// Value: b - Index: 1 - Arguments: Free to play with arguments | |
// Value: c - Index: 2 - Arguments: Free to play with arguments | |
20- CLASS and SUBCLASS | |
Class: | |
function Vehicle(){ | |
} | |
Vehicle.prototype = { | |
engine: true, | |
doors: 4, | |
wheels: 4 | |
} | |
function Coupe() { | |
this.doors = 2 | |
} | |
Subclass | |
Coupe.prototype = new Vehicle() | |
21- SECURE VALUES | |
- If we want to set certain values in an object that cannot be modified, | |
we can do it with Object.defineProperties(obj, {parameters}). Taking the | |
example from before, we change one section: | |
Object.defineProperties(Vehicle.prototype, { | |
engine: { | |
value: true, | |
writable: false | |
}, | |
doors: 4, | |
wheels: 4 | |
}) | |
- The value engine will not be able to be modified: | |
var mazda = new Coupe(); | |
mazda.engine // returns true | |
mazda.engine = false | |
mazda.engine // still returns true | |
- Another example: | |
var obj = {name: 'Object'}; | |
Object.defineProperties(obj, { | |
age: { | |
value: 30, | |
writable: false | |
} | |
}) | |
console.log(obj.age); // 30 | |
obj.age = 32; | |
console.log(obj.age); // 30 | |
22- SECURE OBJECTS PROPERTIES BY CONVENTION | |
- Has no real efect in JS reading the code but by convention indicates | |
other programmers that this property is protected and should not be | |
modified. | |
var Person = (function() { | |
var _trueAge = 50; | |
return { | |
age: _trueAge - 15 | |
}; | |
})(); | |
Person.age // 35 | |
Person._trueAge // undefined | |
23- COPYING OBJECTS WITH jQUERY | |
var Person = (function() { // IIFE function type | |
return { | |
age: 35 | |
} | |
})(); | |
var copy = $.extend(copy, Person.prototype) | |
// copy and Person.prototype share the same properties |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment