-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
week17Hw OK #26
week17Hw OK #26
Conversation
|
||
``` 執行過程 | ||
1.`console.log(1)` 進入 Call Stack 直接執行,印出 1 後從 Call Stack pop | ||
2.`setTimeout(() => { console.log(2) }, 0)` 進入 Call Stack 看到是 setTimeout 把 setTimeout 放到 WebApi 並設置計時器給它,經過 0 秒後會把 `console.log(2)` 放到 callback queue。 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
其實是把 () => { console.log(2) } 放到 callback queue
``` | ||
|
||
`obj.inner.hello()` | ||
上面這個是語法糖的形式,實際上要使用 function 應該是 function call 這個形式,所以我們可以把這段程式碼轉成 `obj.inner.hello.call(obj.inner)`,call 裡面代的值就是 hello 這個 function 前的值,同時這個值就是 this。 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
跟語法糖其實沒關係,我只是說 this 可以用這種形式來「代換」,但不等同於這是語法糖
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
我是看this 的值到底是什么?一次说清楚 裡面有一段提到:
从看到这篇文章起,你一定要记住,第三种调用形式,才是正常调用形式:
func.call(context, p1, p2)
其他两种都是语法糖,可以等价地变为 call 形式:
func(p1, p2) 等价于
func.call(undefined, p1, p2)
obj.child.method(p1, p2) 等价于
obj.child.method.call(obj.child, p1, p2)
请记下来。(我们称此代码为「转换代码」,方便下文引用)
至此我们的函数调用只有一种形式:
func.call(context, p1, p2)
裡面提到這其他兩種都是語法糖才這樣寫的
看到老師回答後,我去找了一下維基對語法糖的定義
語法糖,指電腦語言中添加的某種語法,這種語法對語言的功能沒有影響,但是更方便程式設計師使用。
以這段定義來說,純 function 沒辦法改變 this 的值,所以這樣不算語法糖只是可以代換,不知道這樣對不對?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
原來是文章裡面提到的,我自己是對這說法保持懷疑啦
因為要證明 JS 底層真的是轉成這種形式才能說是語法糖
|
||
另一個難題應該是 this 了,一開始看完 What's THIS in JavaScript? 覺得 this 也沒什麼,信心滿滿的接續看了老師的文章後馬上傻眼XD,範例只答的出一個馬上被打臉,後來也是一篇文章重複看了好幾遍,然後某天就突然通了, call 的方法懂了後真的簡單好用。 | ||
|
||
第一次好好的理解程式語言的底層到底在幹嘛,看了老師的文章真的有了解滿多不同的東西,那個大安 star 的 code 實做出來我有嚇到XD,繼續邁進下一週。 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
那個大安 star 的 code 實做出來我有嚇到
這是什麼?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
所有的函式都是閉包:談 JS 中的作用域與 Closure全域變數就是國際巨星這段,直接把說法轉成程式碼覺得很厲害XD
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
喔喔,我自己都忘記這一段了XDD
麻煩老師了 感謝