###### tags: `mynote` [TOC] # JS Conception --- ## Basic ### == and === **==** 左邊是int type右邊是string type,但是因為兩個等於會把 string 轉型為int,所以實際比對是 1 = 1 所以是true。 **===** 如果是三個等於(===),那麼就不會有轉換型別的問題,因此 1 === "1" //false 就是false。 --- ## Global Ececution Context ==執行JS 後台會執行的事情== ![](https://i.imgur.com/ZSfZ5x5.png) ## Function Execution Context ==JS 後台會執行的事情== ![](https://i.imgur.com/33EmfD0.png) ## Hoisting What is Hoisting?? ==function 或 var 在creation phase會先分配給memory 所以先執行再宣告也不會報錯== ![](https://i.imgur.com/P5sviyr.png) ```javascript= satHi() //Hi function sayHi(){ console.log("Hi") } ``` :::danger function expression(arrow function), const, let都不支援Hoisting, 所以不能先執行再宣告 ::: - initializer(const) ==是否需要先賦予變數值== ## Variables ```javascript= const x // syntax error let y // undefined var z //undefined ``` - re-declaration(var) ```javascript= const x = 1 const x = 2 // syntax error let y = 1 let y = 2 // syntax error var z = 1 var z = 2 // ok! ``` - re-assignment(let, var) ```javascript= const x = 1 x = 2 // syntax error let y = 1 y = 2 // ok! var z = 1 z = 2 // ok! ``` ## Scope - Global Scope(let, var, const) - Function Scope(let, var, const) - Block Scope(let, const) ==it can only be seen inside a loop or if statement== ```javascript= if(true){ var x=1; } conole.log(x) //1 ``` ## Conculsion ![](https://i.imgur.com/AvWbARP.png) ## Closure(Scope chain) ==function 的變數取決於function被定義的scope== ![](https://i.imgur.com/RHLrT8O.png) ![](https://i.imgur.com/IY8l7F3.png) ## CallStack ==是一種資料結構, 遵循last in first out== ![](https://i.imgur.com/wUvASji.png) ## Functions ==All functions are objects== ### Constructor Function [物件原型的詳細介紹(有點多)](https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/Objects/Object_prototypes) ==製作大量相似的obejects== ![](https://i.imgur.com/QurbTfO.png) ```javascript= function Person(name, age){ this.name = name; this.age = age; this.hi = function(){ console.log("Hi") } } let Mike = new Person("Mike", 33) let Lex = new Person("Lex", 38) Mike.hi() // Hi ``` :::warning 如果有共有的function或是property, 可以使用prototype來指向同一個memory位置, 避免memory浪費 ```javascript= function Person(name, age){ this.name = name; this.age = age; } Person.prototype.hi = function(){ console.log("Hi") } let Mike = new Person("Mike", 33) let Lex = new Person("Lex", 38) Mike.hi() // Hi ``` ::: ### Prototype ==Prototype is a simple reference to another object; this object contains common properties and methods across all instances.== string的兩種創建方式 ```javascript= myName = "Dennis" myName = new String("Dennis") ``` :::info 用constructor創造的string就會繼承prototype 但是沒必要這樣做, myName = "Dennis"即可 要使用的時候內建function時候 會自動轉換myName = new String("Dennis") ![](https://i.imgur.com/oeSuRER.png) ::: ### Functions methods ==funtion 內部的this是對應到window而不是function本身== ![](https://i.imgur.com/qjGfEs6.png) - bind 可以將function本身丟回去, 但是要賦予新的變數 ![](https://i.imgur.com/JOvXCYf.png) - call 可以將function本身丟回去, 不用賦予新的變數 ![](https://i.imgur.com/jS6S0iR.png) 也可以傳參數 ![](https://i.imgur.com/ik2a3oh.png) - apply 和call一樣的用法, 只是參數要用list ![](https://i.imgur.com/eKWYuyI.png) ### Prototype Inheritance ![](https://i.imgur.com/ZPypjgO.png) ### Object.creat() 用來繼承prototype![](https://i.imgur.com/lTJSqQ3.png) ### [.__proto__ .prototype差別](https://peter-chang.medium.com/javascripter-%E5%BF%85%E9%A0%88%E7%9F%A5%E9%81%93%E7%9A%84%E7%B9%BC%E6%89%BF%E5%9B%A0%E5%AD%90-prototype-prototype-proto-object-class-inheritace-nodejs-%E7%89%A9%E4%BB%B6-%E7%B9%BC%E6%89%BF-54102240a8b4) ![](https://i.imgur.com/ybq5LuF.png) - Function和Object都是构造函数 - Object.prototype是所有对象的顶层。 - Function的构造器指向自己 ```javascript= function Foo(name) { this.name = name; } var b = new Foo('b'); var a = new Foo('a'); b.say = function() { console.log('Hi from ' + this.whoAmI()); } console.log(a.__proto__ === Foo.prototype); // true console.log(a.__proto__ === b.__proto__); // true ``` ```javascript= //Function的原型对象 console.log(1,Function.prototype); //Object的原型对象 console.log(2,Object.prototype); //Function的原型对象的原型对象 console.log(3,Function.prototype.__proto__); console.log(4,Object.prototype === Function.prototype.__proto__); ``` ![](https://i.imgur.com/Gyaz7uN.png) # JS --- ## Arrow function ```javascript= let sayHi = ()=>{} ``` feature - no hoisting. 一定要先宣告再使用 - no this key word. **(this key word refers to window object)** ## for loop ### map 创建一个新的数组,其中每一个元素由调用数组中的每一个元素执行提供的函数得来。 ```javascript= let arr =[1,2,3,4,5,6] let list = arr.map(value => { return value * value; }); //list = [1,4,9,16,25,36] ```` ### forEach 针对每一个元素执行提供的函数。 ```javascript= let arr =[1,2,3,4,5,6] arr.forEach((value, key) => { return arr[key] = value * value; }); //[1,4,9,16,25,36] ```` ## callback promise async ==一般同步的狀況== 一般同步的狀況2的等待時間比較短會先打印 ```javascript= window.setTimeout(() => {console.log(1)},2000) window.setTimeout(() => {console.log(2)},1000) //2 //1 ```` ==callback的狀況== ```javascript= function delay(message, time) { return new Promise(function (resolve, reject) { window.setTimeout(() => {resolve(`${message}`)}, time)}); } p = delay; p(1,2000).then((a) => { console.log(a); return delay(2, 1000); }).then(b=>console.log(b)) //1 //2 ```` ==Promise的狀況== ```javascript= function delay(message, time) { return new Promise(function (resolve, reject) { window.setTimeout(() => {resolve(`${message}`)}, time)}); } p = delay; p(1,2000).then((a) => { console.log(a); return delay(2, 1000); }).then(b=>console.log(b)) //1 //2 ```` Promise用then接正確的結果, 用catch接錯誤的結果 ```javascript= function delay(message, time) { return new Promise(function (resolve, reject) { window.setTimeout(() => {resolve(`${message}`)}, time)}); } p = delay; p(1,2000).then((a) => { //正確的結果顯示這裡 console.log(a); return delay(2, 1000); }).then(b=>console.log(b)) .catch((err) => { //錯誤的結果顯示這裡 console.log("err", err); }); //1 //2 ```` ==ASYNC的狀況== ```javascript= function delay(message, time) { return new Promise(function (resolve, reject) { window.setTimeout(() => {resolve(`${message}`)}, time)}); } async function test(){ console.log(await delay(1,2000)) console.log(await delay(2,1000)) } test() ``` ## Destructing ![](https://i.imgur.com/lN38DJb.png) ## AJAX and API AJAX = Asynchronous JavaScript And XML Q: Why AJAX? A: connect with API ### fetch API promise ```javascript= fetch(requestURL) .then((response) => { return response.json(); }) .then((data) => { console.log(`Title: ${data.title}`); if (data.completed !== true){ console.log("Undo"); } else { console.log("Done!!"); } }) .catch((error) => { console.log(`Error: ${error}`); }) ``` async ```java= const Find = async () => { const dataFetch = await fetch( "https://dennis89linebot.herokuapp.com/myNote", { method: "GET", headers: { Accept: "application/json", }, } ); let parseData = await dataFetch.json(); setDatas(parseData); console.log("first", parseData); }; ``` :::danger fetch如果不用async or promise 下面的code會先執行,導致沒有讀到值 ```javascript= const dataFetch1 = fetch( "https://dennis89linebot.herokuapp.com/myNote", { method: "GET", headers: { Accept: "application/json", }, } ); let parseData1 = dataFetch1.json(); ``` ![](https://i.imgur.com/j05wyBM.png) ::: ### CORS issue(同網域下才requast API) [https://ithelp.ithome.com.tw/articles/10268821](https://ithelp.ithome.com.tw/articles/10268821) # FAQ ## [import时如何正确使用花括号'{ }'](https://)