Skip to content

Commit 159135f

Browse files
committed
Basic concept of How-JS-Works
1 parent fbe57b5 commit 159135f

File tree

3 files changed

+90
-0
lines changed

3 files changed

+90
-0
lines changed

How-JS-Works/Hoisting.js

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// functions
2+
calculateAge(1965); // 51
3+
4+
function calculateAge(year) {
5+
console.log(2016 - year);
6+
}
7+
8+
9+
// retirement(1956);
10+
var retirement = function (year) {
11+
console.log(65 - (2016 - year));
12+
}
13+
14+
15+
// variables
16+
console.log(age); // Undefiened
17+
var age = 23;
18+
19+
function foo() {
20+
console.log(age); // Udefined
21+
var age = 65;
22+
console.log(age); // 65
23+
}
24+
25+
26+
foo();
27+
console.log(age); // 23

How-JS-Works/Scoping.js

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// First scoping example
2+
var a = 'Hello!';
3+
first();
4+
5+
function first() {
6+
var b = 'Hi!';
7+
second();
8+
9+
function second() {
10+
var c = 'Hey!';
11+
console.log(a + b + c); // Hello!Hi!Hey!
12+
}
13+
}
14+
15+
// Example to show the differece between execution stack and scope chain
16+
var a = 'Hello!';
17+
first();
18+
19+
function first() {
20+
var b = 'Hi!';
21+
second();
22+
23+
function second() {
24+
var c = 'Hey!';
25+
third()
26+
}
27+
}
28+
29+
function third() {
30+
var d = 'John';
31+
// console.log(c); // c is not defined
32+
console.log(a + d); // Hello!John
33+
}

How-JS-Works/This.js

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// console.log(this); // {}
2+
calculateAge(1985);
3+
4+
function calculateAge(year) {
5+
console.log(2016 - year);
6+
console.log(this);
7+
}
8+
9+
var john = {
10+
name: 'John',
11+
yearOfBirth: 1990,
12+
calculateAge: function () {
13+
console.log(this);
14+
console.log(2016 - this.yearOfBirth);
15+
16+
function innerFunction() {
17+
console.log(this);
18+
}
19+
innerFunction();
20+
}
21+
}
22+
23+
john.calculateAge();
24+
var mike = {
25+
name: 'Mike',
26+
yearOfBirth: 1984
27+
};
28+
29+
mike.calculateAge = john.calculateAge; // borrowing calculateAge function from john object
30+
mike.calculateAge();

0 commit comments

Comments
 (0)