# Javascript Introduction
###### tags: `f2e`
## Andy Tsai
---
## Agenda
- what is javascript
- 具備能力?
- 基礎語法
- Javascript語言特性
- Javascript小技巧
- ECMAScript 2015(ES6)
- Framework
- 推薦網站
---
## what is javascript
----
![](https://i.imgur.com/izJav9s.png)
----
<img src="https://i.imgur.com/QCHc8KF.png" width="300" />
----
<img src="https://i.imgur.com/762mepR.png" width="350" />
----
<img src="https://i.imgur.com/NaRZopS.png" width="380" />
---
## 具備能力?
----
## [前端技能樹](http://www.dungeonsanddevelopers.com/#_ab_13_Your%20Name)
## [在 2016 年學 JavaScript 是一種什麼樣的體驗?](https://zhuanlan.zhihu.com/p/22782487)
----
## 一開始
![](https://i.imgur.com/YJgtDQA.png)
----
## 過一陣子
![](https://i.imgur.com/jD0Jnu9.jpg)
----
## 現在
![](https://i.imgur.com/bzHcgqf.jpg)
----
## 電腦:每過18個月會將晶片的效能提高一倍
----
## 前端:每過18個月難度提高一倍
----
## 前端每年都要砍掉重練
![](https://i.imgur.com/E2Z1HVd.jpg)
----
## 好像有點絕望?
![](https://i.imgur.com/PlIqdK7.jpg)
----
## 沒關係啦 反正最底層都是JS
---
## 基礎語法
- [JavaScript 標準參考教程](http://javascript.ruanyifeng.com/)
- var
- Number
- String
- Boolean
- undefined
- 弱型態
- Array
- Function
- Object
- 建構函數
----
### var
- 變數本身無需宣告型態,型態決定於值本身
```
var number = 10;
var str = "Hello";
var bool = true;
var array = [];
```
----
### Number
```
var num = 100;
parseInt("500", 10);
isNaN(1); // false
isNaN('a'); // true
```
----
### String
```
var text = 'Hello World';
text.length; // 11
text.replace('World', 'JS'); // Hello JS
text.toUpperCase(); // HELLO WORLD
```
----
### Boolean
```
Boolean(false) // false
Boolean(0) // false
Boolean('') // false
Boolean(null) // false
Boolean(undefined) // false
Boolean(NaN) // false
```
----
### undefined
```
只要一個變數在初始的時候未給予任何值的時候,就會產生 undefined
var a;
typeof a; // undefined
```
----
### 弱型態
```
number、string與boolean,會在必要的時候
自動型態轉換為對應的包裹物件
'6' + 2 // '62'
2 + '6' // '26'
'6' - '2' // 4
'6' - 2 // 4
'6' * '2' // 12
'6' / '2' // 3
1 + true // 2
1 + false // 1
```
----
### typeof
```
typeof 1; // 'number'
typeof 'Hello'; // 'string'
typeof false; // 'boolean'
typeof []; // 'object'
typeof {}; // 'object'
typeof null; // 'object'
typeof undefined; // 'undefined'
```
----
### Array
```
var array = [
10,
"Hello",
false,
{a:1},
function(){alert("Hello")}
];
```
----
### Function
```
function print(s) {
console.log(s);
}
or
var print = function(s) {
console.log(s);
}
print('Hello');
```
----
### Object
```
{ key: value }
```
```
// bad
var person = new Object();
person.name = 'Andy';
person.age = 27;
person.speak = function() {
alert('Hello');
}
// good
var person = {
name: 'Andy',
age: 27,
speak: function() {
alert('Hello');
}
}
```
----
### 建構函數
```
function Person(name, age){
this.name = name;
this.age = age;
}
var person = new Person("Andy", 27);
console.log(person.name); // 'Andy'
console.log(person.age); // 27
```
---
## Javascript小技巧
----
## 使用object儲存資料
```
var _class = {
name: '一年一班',
students: [{
name: '學生1',
seatNo: 1
}, {
name: '學生2',
seatNo: 2
}]
}
for(var i=0; i<_class.students.length; i++) {
var student = _class.students[i];
console.log(student.name);
console.log(student.seatNo);
}
```
----
## call by value
- string, number, boolean
```
var a = 1;
var b = a;
b = 2;
// a = 1
// b = 2
1 == 1 // true
```
----
## call by reference
- array, object
- [lodash](https://lodash.com/)
```
var a = [1,2,3];
var b = a;
b.push(4);
// a = [1,2,3,4]
// b = [1,2,3,4]
var a = {t:1};
var b = a;
b.t = 2;
// a = {t:2}
// b = {t:2}
[1] == [1] // false
{a:1} == {a:1} // false
```
----
## 預設值
```
function Person(name, age){
this.name = name || 'person';
this.age = age || 18;
}
var p1 = new Person('Andy', 27);
// 'Andy' 27
var p2 = new Person();
// 'person' 18
```
----
## replace all
- [正規表示式](https://goo.gl/IThKpE)
```
var s1 = "A.B.C";
s1.replace(/\./g,"_"); // "A_B_C"
```
----
## 使用===判斷
```
10 == '10' // true
10 === '10' // false
10 != '10' // false
10 !== '10' // true
```
----
## 给函數傳遞参數(傳遞object比傳遞一堆參數好)
```
function person(obj) {
console.log(obj.name);
console.log(obj.age);
}
var data = {name:'andy', age: 27};
person(data);
// 'andy'
// 27
```
----
#### Array - join
```
var arr = ["jack", "john", "may", "su", "Ada"];
var str = arr.join("、");
// "jack、john、may、su、Ada"
```
----
#### Array - concat
```
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
var alphaNumeric = alpha.concat(numeric);
// ["a", "b", "c", 1, 2, 3]
```
----
#### Array - map
```
var numbers = [1,2,3,4,5,6,7,8,9,10];
var newNumbers = numbers.map(function(element, index) {
return element * 2;
});
// [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
```
```
// bad
var count = 0;
numbers.map(function(element) {
count++;
return element * 2;
});
```
----
#### Array - filter(ES6)
```
var numbers = [1,2,3,4,5,6,7,8,9,10];
var newNumbers = numbers.filter(function(number){
return number % 2 == 0;
});
// [2, 4, 6, 8, 10]
```
---
## Javascript語言特性
- document
- prototype
- scope
- closure
- callback
----
### document - dom loaded
```
<body onload="myFunction()">
</body>
<script>
function myFunction() {
document.getElementById('text').value = 'text';
}
</script>
```
```
// jQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$().ready(function() {
$('#text').val('tet');
})
</script>
```
----
### document - selector
```
<button id="btn1" class="btn"/>
document.getElementById('btn1');
document.getElementsByClassName('btn');
document.getElementsByTagName('button');
```
```
// jQuery
$('#btn1') // id selector
$('.btn') // class selector
$('button') // element selector
```
----
### document - get value
```
<input id="search" type="text" value="123" />
document.getElementById('search').value; // 123
```
```
// jQuery
$('#search').val(); // 123
```
----
### document - eventHandler
```
<button id="btn1" class="btn"/>
document.getElementById('btn1').onclick = function(){
alert('Hello');
}
```
```
// jQuery
$('#btn1').click(function() {
alert('Hello');
})
```
----
### append element
```
<ul id="list"></ul>
$('#list').append('<li>item1</li>')
<ul id="list">
<li>item1</li>
</ul>
```
----
### prototype
```
function Person(name, age) {
this.name = name;
this.age = age;
this.toString = function() {
return '[' + this.name + ', ' + this.age + ']';
};
}
```
```
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.toString = function() {
return '[' + this.name + ', ' + this.age + ']';
};
```
----
### scope
- 使用var所宣告的變數,作用範圍是在當時所在環境
- JavaScript在查找變數時,會循著範圍鏈(Scope chain)一層一層往外找
----
#### 範例1
```
var x = 10;
function func() {
console.log(x);
}
func();
// 10
```
----
#### 範例2
```
var x = 10;
function func() {
console.log(x);
var x = 20;
console.log(x)
}
func();
// undefined
// 20
```
----
### closure
- 閉包是個特殊的物件,他包含了一個函式,以及函式被建立時所在的環境
- 環境是:" 環境由任意的局域變數所組成,這些變數是由在閉包建立的時間點上存在於作用域裡的所有變數"
```
function sum() {
var x = 10;
return function (y) {
console.log(x+y);
}
}
var func = sum();
func(200); // 210
```
----
### 範例
- [範例1](https://codepen.io/bbandydd/pen/mXwjPJ)
- [範例2](https://codepen.io/bbandydd/pen/MQoBXq)
----
### callback
```
將函式當作另一個函式的參數,由另外的函式來呼叫
function 接電話(name, phone, doSomething) {
console.log('來電者:' + name + ', 號碼:' + phone);
doSomething();
}
function 打招呼() {
alert('Hello');
}
接電話('Andy', '0987654321', 打招呼);
```
----
## Yeah!! 學會Javascript了!!
![](https://i.imgur.com/YiSaldV.png)
----
## 以上,都是舊的寫法(ES5)
---
## ECMAScript 2015(ES6)
- [ECMAScript 6入門](http://es6.ruanyifeng.com/)
- default value
- let const
- String template
- arrow function
- class
- 解決callback hell
----
### what is ECMAScript
- 將JavaScript提交给國際標準化組織ECMA
- 標準在每年的6月份正式發布一次
- 目前最新版本ECMAScript 2016(ES7)
----
### Babel
- [Babel入門](http://www.ruanyifeng.com/blog/2016/01/babel.html)
- Babel是一個轉碼器,可以將ES6轉為ES5,從而在瀏覽器執行
```
// 轉碼前
input.map(item => item + 1);
// 轉碼後
input.map(function (item) {
return item + 1;
});
```
----
### default value
```
ES5:
function Person(name, age){
this.name = name || 'person';
this.age = age || 18;
}
ES6:
function Person(name = 'person', age = 18){
this.name = name;
this.age = age;
}
```
----
### let const
```
用法類似於var,但只在所在的區塊內有效
let是更完美的var
const定義時設定初值,之後不允許再改變
1. 宣告的變數有區塊作用域
2. 禁止在同一活動範圍中再次宣告相同名稱的變數
3. 禁止在宣告變數之前就使用它
ES5:
var a = 1;
ES6:
let b = 2;
const c = 3;
```
- [範例1](https://codepen.io/bbandydd/pen/zRzLzM)
- [範例2](https://codepen.io/bbandydd/pen/xYrJQv)
----
### String template
```
ES5:
var name = firstName + '_' + lastName;
ES6:
let name = `${firstName}_${lastName}`;
```
----
```
ES5:
var SQL = 'SELECT * ' +
'FROM TABLE ' +
'WHERE NAME="' + name + '"'
ES6:
const SQL =
`
SELECT *
FROM TABLE
WHERE NAME='${name}'
`
```
----
### arrow function
```
ES5:
var Person = function(name) {
console.log(name);
}
ES6:
const Person = (name) => {
console.log(name);
}
```
----
### class - ES5
```
ES5:
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.say = function() {
alert('Name:' + this.name +', Age:' + this.age);
}
var person = new Person("Andy", 27);
person.say();
```
----
### class - ES6
```
ES6:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
say() {
alert(`Name:${this.name}, Age:${this.age}` );
}
}
let person = new Person('Andy', 27);
person.say();
```
----
## callback hell
- API A -> API B -> API C
![](https://i.imgur.com/JQpQhzz.jpg)
----
### 解決callback hell
- [參考連結](http://huli.logdown.com/posts/292655-javascript-promise-generator-async-es6)
- callback hell
- promise
- generator
- async await (ES7)
---
## Framework
----
## 前端:[jQuey](http://codepen.io/bbandydd/pen/WoRMeV) [AngularJS](http://codepen.io/bbandydd/pen/dONdym) [VueJS](http://codepen.io/bbandydd/pen/GNrQKY) [ReactJS](http://codepen.io/bbandydd/pen/bBgLEX?editors=1010)
## 後端:Express Koa
## APP:Ionic [ReactNative](https://github.com/fangwei716/30-days-of-react-native)
## 桌面應用程式:[Electron](http://electron.atom.io/)
----
## Q & A
{"metaMigratedAt":"2023-06-14T12:02:13.837Z","metaMigratedFrom":"Content","title":"Javascript Introduction","breaks":true,"contributors":"[{\"id\":\"e23ef62f-a089-4a28-8ce7-817212441f68\",\"add\":27,\"del\":7}]"}