Javascript

Tags
javascript
Last edited
Last updated January 27, 2023
Duration
 

型別

 

 

定義

  • varfunction scope
  • letblock 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) 延遲執行(一次)
💡
另外setTimeoutsetInterval在執行之後都會回傳一個timerid,如果要取消計時可以使用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

notion image
 
notion image
這邊會發現當我們每次使用.then()方法的時候,都會重新創建一個promise的物件,然後接續下去(所以Promise.then方法才可以無限延續)

其他應用

 

參考資料

  • 白皮書
  • React官方