javascript - es6數值解構Number.prototype.toString is not generic
問題描述
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Document</title></head><body> <script>({toString:b} = 123);console.log(b === Number.prototype.toString); // trueconsole.log(Number.prototype.toString()); // 0console.log(b()); // Number.prototype.toString is not genericlet num = 456;console.log(num.b()); // num.b is not a function </script></body></html>
為什么b不能作為函數調用?
問題解答
回答1:Number.prototype.toString 標準
The toString function is not generic; it throws a TypeError exception if its this value is not a Number or a Number object. Therefore, it cannot be transferred to other kinds of objects for use as a method.
翻譯一下后面的:
如果他的this值不是數字類型或者Number對象,將會拋出一TypeError
直接調用this是window你可以這么用:
b.call(1)b.call(Number(’test’))回答2:
你可以b.call(num),一般來說toString不允許作為普通函數執行很容易接受,就跟構造函數一般不作為普通函數執行一樣。ps:例子中的Number.prototype.toString()實際上作用域也是Number.prototype
補充一下,答題有點離題了,b()實際上是作為函數調用的,也調用成功了,錯誤是toString()自身拋出來的。
回答3:Number.prototype.toString 可以作為函數調用但 this 一定要是 Number 類型。其他類型的 toString 同理。
b.call(123)// '123'
The toString function is not generic; it throws a TypeError exception if its this value is not a Number or a Number object. Therefore, it cannot be transferred to other kinds of objects for use as a method.
15.7.4.2 Number.prototype.toString
相關文章:
1. sql語句 - mysql中關聯表查詢問題2. css - chrome下a標簽嵌套img 顯示會多個小箭頭?3. javascript - 如何將一個div始終固定在某個位置;無論屏幕和分辨率怎么變化;div位置始終不變4. html - vue項目中用到了elementUI問題5. javascript - iframe 為什么加載網頁的時候滾動條這樣顯示?6. python - django models 為生成的html元素添加樣式。7. javascript - vscode alt+shift+f 格式化js代碼,通不過eslint的代碼風格檢查怎么辦。。。8. javascript - 有什么比較好的網頁版shell前端組件?9. mysql updtae追加數據sql語句10. javascript - 原生canvas中如何獲取到觸摸事件的canvas內坐標?
