型別
- Undefined 未定義
定義
var
→function scope
let
→block scope
const
→ 常數(不可以進行修改)
函式
定義函式
- 一般的函式
CODE
function a(x1,x2){ return x1+x2; }
- 箭頭函式(Arrow Function)
CODE
//直接回傳 ()=>(n) //程式碼 ()=>{ alert(1); return n; } //命名 a=()=>{ alert(1); }
*參數預設可以不用放在後面
常用函式
setInterval(
function
,
ms
)
背景重複執行
setTimeout(
function
,
ms
)
延遲執行(一次)
另外
setTimeout
和setInterval
在執行之後都會回傳一個timer
的id
,如果要取消計時可以使用clearTimeout(id)
等方式進行清除物件
物件原型——類(Class)
定義
- 物件方法
- 靜態方法
Static Method
(綁定類別) - 非靜態方法(綁定物件實體)
直接用類別名稱進行呼叫
直接用物件實體名稱進行呼叫
- 物件屬性
- 建構式 (init)
CODE
class CZR{ constructor(){//__init__ 初始化函數 console.log('I amd timothychen') this.name='timothychen'; }; age=1; //method run(){ console.log('run'); } stop(){ console.log('stop'); } }
產生實體
CODE
czr=new CZR();
繼承
繼承所有的
Class A extends B
必須在
constructor
中先呼叫super()
呼叫父類別的建構式this
這個
this
通常在物件導向的時候就跟其他的程式語言沒有太大的區別就是表示建立的那一個物件實體。但是javascript
不一樣的是this
可以在全域呼叫(就是可以不用在class
和物件也一樣可以使用this這個關鍵字)脫離了物件導向之後
this
所指向的內容就是全域的物件(除非在嚴格環境下會是undefined
)。但是也可以手動修改
this
的值'use strict'; function hello(a, b){ console.log(this, a, b) } hello.call('yo', 1, 2) *// yo 1 2* hello.apply('hihihi', [1, 2]) *// hihihi 1 2
call()
就跟一般的呼叫函數沒有區別,只是第一個參數變成了this
的值
apply()
跟call
很類似,只是將所有的參數pack
到了一個array
裡面一起傳到hello
這個函數中
bind()
非同步程式
時間排程
- setTimeout()
window.setTimeout()
和setTimeout()
在網頁中的執行是一樣的,因為setTimeout
會自己去找當時環境的global obj
,瀏覽器中的global obj
就是window
,但是如果不在瀏覽器中window.setTimeout
就會無法使用
- setInterval()
AJAX
var req=new XMLHTTPRequest(); req.open(method,url); req.onload=function(){ alert(this.responseText); }; req.send();//發出請求(背景發出)
Promise
這邊會發現當我們每次使用
.then()
方法的時候,都會重新創建一個promise
的物件,然後接續下去(所以Promise
的.then
方法才可以無限延續)其他應用
參考資料
- 白皮書
- React官方