JavaScript Introduction
Forked from Jong-Shian Wu
Lasted updated: 26/11/2015
Javascript History
As is well known at this point, I created JavaScript in ten days in May 1995, under duress and conflicting management imperatives—“make it look like Java,” “make it easy for beginners,” “make it control almost everything in the Netscape browser.”
─Brendan Eich
//print 'hello'
function() {
console.log('hello');
}
//call hello() per 1s.
setInterval(function(){
hell();
},1000);
hello = 3;
// Uncaught TypeError:
// hello is not a function
ECMAScript 5.1
We are talking about
We are not focus on the browser-specific features and things provided.
ECMAScript 6
By the way
Released on June,2015
You can find ES 6 compatibility table here
Hello World!
console.log("Hello World!");
+
F12
Chrome Developer Tools
Variable
Variables are named containers. They serve as holders for values
var x;
var foo = 1,
bar = 'text';
x
bar
foo
undefined
1
'text'
var x;
var foo = 1,
bar = 'text';
x = false;
bar = 123;
x
bar
foo
false
1
123
You can re-assign another value to a variable
var $foo = "blablabla";
var 變數 = "var";
Identifiers
Identifiers are used to name variables, the first character must be a letter, an underscore (_), or a dollar sign ($).
arguments、break、case、catch、class、const、
continue、debugger、default、delete、do、else、
enum、eval、export、extends、false、finally、
for、function、if、implements、import、in、
instanceof、interface、let、new、null、package、
private、protected、public、return、static、super、
switch、this、throw、true、try、typeof、var、
void、while、with、yield
Reserved Words
Type
Primitive types
Object types
There are 5 primitive types
Primitive types
Object types
Number
Undefined
Boolean
String
Null
undefined
true
false
null
'single quotes'
" "
"\n"
"\u003e"
' "hello" '
" \"world\" "
Unicode character
NaN
.14
3.14
2e+4
-Infinity
-0
0x11
IEEE 754 64-bit (double)
Primitive Type & their primitive value
UTF-16
Undefined
typeof notExist; // "undefined"
var foo;
typeof foo; // "undefined"
function nothing() {}
nothing(); // "undefined"
Number
Boolean
String
Null
Primitive Type
var foo = null;
foo; //null
null == false; //true
/*DOM*/
document.getElementById('notExist');// null
primitive value that represents the intentional absence of any object value
null
Undefined
Number
Boolean
String
Null
Primitive Type
var bool = false;
Boolean(bool); // false
Boolean(null); // false
Boolean(-Infinity); // false
Boolean(undefined); // false
Boolean(0); //false
Boolean(""); //false
Boolean(-1); //true
"0" == 0; //true
"0" === 0; //false
Undefined
Number
Boolean
String
Null
Primitive Type
假值(falsy):
- false
- 0
- -0
- ""
- NaN
- null
- undefined
function point(x, y) {
if (!x) {
x = 320;
if(!y) {
y = 240;
}
return {x: x, y: y}
}
point(0,0); //{x:320, y:240}
Undefined
Number
Boolean
String
Null
Primitive Type
假值(falsy):
- false
- 0
- -0
- ""
- NaN
- null
- undefined
var num1 = 100;
var num2 = Number("100");
-1 / 0; // -Infinity
1 / 0; // Infinity
-1 * 0; // -0
0 === -0; // true
/* NaN means "Not a Number" */
isNaN("hello!"); // true
typeof NaN; //number
NaN === NaN // false
NaN not equal itself
Undefined
Number
Boolean
String
Null
Primitive Type
isNaN(NaN); // true
isNaN("foo"); // true
isNaN(undefined); //true
isNaN({}); //true
Undefined
Number
Boolean
String
Null
Primitive Type
var a = NaN;
a !== a; //true
var b = "foo";
b !== b ; //false
0.1 + 0.2; //0.30000000000000004
0.2 + 0.4; //0.6000000000000001
(1 + 2) /10; //0.3
Number.MAX_SAFE_INTEGER; // 9007199254740991
Undefined
Number
Boolean
String
Null
Primitive Type
var hello = "hello";
var omega = '\u2126';
omega; //"Ω"
Unicode escape sequence
Undefined
Number
Boolean
String
Null
Primitive Type
var hello = "hello";
hello.length; // 5;
'𝌆'.length; // 2
//'𝌆' == '\uD834\uDF06'
Undefined
Number
Boolean
String
Null
Primitive Type
1 == "1"; // true
1 === "1"; // false
1 == true; // true
1 === true; // false
Undefined
Number
Boolean
String
Null
Implicit Coercions
Primitive types
Object types
Object
object
An object is a collection of properties
{name: "Peter"}
Key
Value
Other programming languages have similar concepts, e.g., Map,Dictionary, Hash Table
Object Literal
var obj = {
a: "123456",
b: "asdfgh",
n1: 1,
n2: 2,
"": "Hello!"
};
var obj = new Object;
obj.a = "123456";
obj.b = "asdfgh";
obj.n1 = 1;
obj.n2 = 2;
obj[""] = "Hello!";
Use curly braces to initialize a new object
The code left-side exactly same the right-side
=
Get/Add/Set/Delete properties
var obj = {
1: "one",
name: "Peter",
gender: "male",
"favorite fruit": "banana"
};
obj["age"] = 34; //add and set a property
obj.gender = "female" // set
obj.name; // get
obj["favorite fruit"]; // get
delete obj[1]; // delete
Any value of object is actually a reference
var obj = {
name = "Peter"
};
0x????
obj
ref: 0x????
name: "Peter"
var obj2 = obj;
obj2.name = "Mango";
obj2
ref: 0x????
0x????
name: "Mango"
obj.name; // Mango
Object
function
A function is an object which callable.
var fn = function() {
}
function fn() {
}
Function Expression
Function Declaration
Function Expression (1/2)
A Function Expression defines a function as a part of a larger expression syntax (typically a variable assignment )
var foo = function(bar) {
var str = 'hi ';
return str + bar;
};
console.log(foo('Peter'));
// hi peter
Function Expression (2/2)
Functions defined via Functions Expressions can be named or anonymous
(function(bar) {
var str = 'hi ';
return str + bar;
});
Function Expression Can Be Named
var foo = function fib(n) {
if (n === 0) return 0;
if (n === 1) return 1;
if (n > 1) return fib(n - 1) + fib(n - 2);
};
foo(10); //55
fib(10); // ReferenceError: fib is not defined
The name “fib” is accessible
only inside the function itself
function Identifieropt ( FormalParameterListopt ) { FunctionBody }
Function Invocation
Invoking function each time, it has its own variable scope
with local variables , parameters and arguments
var str = "hello";
var foo = function(bar) {
var str = 'hi ';
return str + bar;
};
console.log(foo("petter"));
console.log(str);
// "hi Petter"
// "hello"
Function parameters not need matched
var foo = function(arg1, arg2){
console.log(arg1, arg2);
console.log(arguments);
}
foo('a');
foo('a', 'b');
foo('a', 'b', 'c', 'd');
//result:
// a, undefined
// ["a"]
// a, b
// ["a", "b"]
// a, b
// ["a", "b", "c", "d"]
Function Returning
var foo = function() {
return;
};
var bar = function() {
}
foo();
// undefined
bar();
// undefined
Function not necessarily need return values explicitly
Function Declaration
A Function Declaration defines a named function variable without requiring variable assignment.
function foo() {
return 'bar';
}
function Identifier ( FormalParameterListopt ) { FunctionBody }
Invoke After A Function Expression
JavaScript interpreter will think that we are writing a
“function declaration” when we start with the keyword
“function” as a JavaScript “statement”.
We can to force it to think about “an expression” using the grouping operator. In fact, any appropriate operator would
work just fine if you do not care about the return value.
(function () {
return 123;
})(); // 123
(function(){ return 'hi'; })(); // "hi"
!function(){ console.log('ya'); }(); // "ya"
+function(){ console.log('ya'); }(); // "ya"
void function(){ console.log('ya'); }(); // undefined
Run-time Hoisting (1/5)
Now , we called a function before function declaration
foo();
function foo() {
console.log('hi');
}
// hi
Why?
Run-time Hoisting (2/5)
JavaScript interpreter move all declarations to the top of the current scope
foo();
function foo() {
console.log('hi');
}
function foo() {
console.log('hi');
}
foo();
This feature also occurs function inside
Run-time Hoisting (2/5)
function foo() {
return bar();
function bar() {
return 'hi';
}
}
console.log(foo()); // hi
function foo() {
function bar() {
console.log('hi');
}
return bar();
}
foo(); // hi
What is Result Each Case ? (1/3)
function foo(){
function bar() {
return 3;
}
return bar();
function bar() {
return 8;
}
}
console.log(foo());
console.log(foo()) = ?
// 8
What is Result Each Case ? (2/3)
var str = "hey";
function foo() {
return str;
var str = "hi";
}
console.log(foo());
console.log(foo()) = ?
// undefined
What is Result Each Case ? (3/3)
function foo(){
return bar();
var bar = function() {
return 3;
};
var bar = function() {
return 8;
};
}
console.log(foo());
console.log(foo()) = ?
// TypeError
Run-time Hoisting (3/5)
var str = "asdf";
function foo() {
return name;
var name = "Peter";
}
foo();//undefined
function foo() {
var name;
name = "Peter";
return name;
}
var str;
str = "asdf";
foo();//undefined
Run-time Hoisting (4/5)
Hoisting order
- Native object (this, arguments)
- Function parameters
- Function declaration
- var declaration
Run-time Hoisting (5/5)
function foo(param) {
console.log(bar);
console.log(param);
console.log(arguments);
say();
var bar= "xxx";
function say() {
console.log('hi');
}
return 'done';
}
foo('a','b');
// undefined
// a
// ["a", "b"]
// hi
// "done"
Result = ?
Run-time Hoisting (5/5)
function hoisting (param) {
arguments;
param;
function sayHello() {
console.log('hello');
}
var bar;
console.log(bar);
console.log(param);
console.log(arguments);
sayHello();
bar = "xxx";
return 'done';
}
foo('a','b');
// undefined
// a
// ["a", "b"]
// hi
// "done"
Result
- arguments
- parameters
- function declaration
- var declaration
Object
object
A method is a function as some object's property
function
+
Methods of an object
// The cat object has three properties
// cat.age, cat.meow, and cat.walk
var cat = {
age:3,
say:function() {
return 'meow~'
}
}
cat.walk = function() {return 'walk'};
cat.say(); // meow~
cat.walk(); // walk
Scenario Analysis |
There's a Bob's source code
var cat = {
age:3,
say:function() {
return 'meow~'
}
}
cat.walk = function() {return 'walk'};
cat.say(); // meow~
Bob
Scenario Analysis |
Some day...
/*
cat obj here;
*/
cat.say = function() {
return 'moooo~~';
}
Scenario Analysis |
/*
code here
*/
cat.say(); // moooo~~
Bob
Closures
closure
A closure is a pair of a function and an environment for resolving free variables
When we use non-local variables...
var a =1;
function foo() {
return a;
}
foo(); //1
a = 2;
foo(); //2
a = "hello";
foo();// hello
Create A Closure (1/5)
var foo = function() {
var a = 1;
var bar = function() {
console.log(a);
}
return bar;
};
var bar = foo();
foo = null;
bar(); //1
Create A Closure (2/5)
var foo = function() {
var a = 1;
return function() {
console.log(a);
};
};
var bar = foo();
foo = null;
bar(); //1
Create A Closure (3/5)
var foo = function() {
var a = 1;
return function() {
console.log(a);
};
};
var bar = foo();
var bar2 = foo();
foo = null;
bar(); //1
bar2(); //1
A closure is created each time
foo returns.
Create A Closure (4/5)
var foo = (function() {
var a = 1;
return function() {
console.log(a);
};
})();
foo (); //1
A closure is created when the
anonymous function returns.
Create A Closure (4/5)
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
console.log (add5(2)); //7
Create A Closure (4/5)
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
console.log (add5(2)); //7
add5 = function(y) {
return 5 + y;
}
Create A Closure (5/5)
function addLinks(){
for (var i = 0; i < 5; i += 1) {
link = document.createElement("a");
link.innerHTML = "Link" + i + '\n';
link.onclick = function() {
alert(i);
};
document.body.appendChild(link);
}
} // end addLinks();
window.onload = addLinks();
We creates 5 elements, adds the value of i as a text to each element and an onclick which is expected to alert the value of i for that link.
Create A Closure (5/5)
Create A Closure (5/5)
function addLinks(){
for (var i = 0; i < 5; i += 1) {
link = document.createElement("a");
link.innerHTML = "Link" + i + '\n';
link.onclick = (function (num) {
return function () {
alert(num);
};
})(i);
document.body.appendChild(link);
}
} // end addLinks();
window.onload = addLinks();
Apply the value of i to the onclick event of the a element, it gets the exact value of i at just that moment in time
Create A Closure (5/5)
Create A Closure (6/5)
var fnArr = [];
for(var i =0; i < 5; i++) {
fnArr.push(function() {
console.log(i);
});
}
for(var idx in fnArr){
fnArr[idx]();
}
//5
//5
//5
//5
//5
Create A Closure (7/5)
var fnArr = [];
for(var i =0; i < 5; i++) {
fnArr.push((function(val) {
return function(){
console.log(val);
}
})(i));
}
for(var idx in fnArr){
fnArr[idx]();
}
//0
//1
//2
//3
//4
fnArr[0] = function() {
return 0;
}
Module
Object
object
Now, using object, function and closure to create module
function
+
closure
The BlogModule Example
Now, we want to create a Blog Module...
var BlogModule= {
name:'my BLog',
addTopic: function() {
//do something
}
};
The BlogModule Example
var BlogModule = (function() {
var my = {},
_name = 'my blog';
function _addTopic(data) {
// do something here
}
my.name = _name;
my.addTopic = function (data) {
_addTopic(data);
};
return my;
}());
The BlogModule Example
console.log(BlogModule);
Let's see what BlogModule exactly inside
Extend BlogModule
var BlogModule = (function(my) {
my.AddPhoto = function () {
// do something here
};
return my;
}(BlogModule));
Extend BlogModule
var BlogModule = (function(my) {
my.AddPhoto = function () {
// do something here
};
return my;
}(BlogModule || {} ));
BlogModule Method Overloading
var BlogModule = (function (my) {
var oldAddPhotoMethod = my.AddPhoto;
my.AddPhoto = function () {
// new code here
};
return my;
} (BlogModule));
Enumerate An Object
var obj = {
a:1,
b:2
}
for (key in obj) {
console.log(key + ' : ' + obj[key]);
}
Enumerate An Object
Inheritance BlogModule
var newModule = (function (old) {
var my = {},
key;
for (key in old) {
if (old.hasOwnProperty(key)) {
my[key] = old[key];
}
}
var oldAddPhotoMethod = old.AddPhoto;
my.AddPhoto = function () {
// re-write code
};
return my;
} (BlogModule));
copy old Module to new Module
BlogModule's SubModule
BlogModule.SubModule = (function () {
var my = {};
// blalblabla
my.foo = function() {
//do something
};
return my;
} ());
BlogModule's SubModule
console.log(BlogModule);
The end
-
this
-
Object.defineProperty
-
The new operator
- JavaScript prototype chain
What' Next?
Some Reference
JavaScript Introduction
By mangogan
JavaScript Introduction
- 915