搜尋

首頁  >  問答  >  主體

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); // true
console.log(Number.prototype.toString()); // 0
console.log(b()); //  Number.prototype.toString is not generic

let num = 456;
console.log(num.b()); // num.b is not a function
    </script>
</body>
</html>

為什麼b不能當函數呼叫?

扔个三星炸死你扔个三星炸死你2818 天前909

全部回覆(3)我來回復

  • 滿天的星座

    滿天的星座2017-06-28 09:31:13

    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 other object. Therefore, it cannot be transferred to other other objects s.

    翻譯一下後面的:

    如果他的
    this

    值不是數字類型或Number對象,將會拋出一TypeError

    直接呼叫
    this

    window你可以這麼用:

    b.call(1)
    b.call(Number('test'))

    回覆
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-28 09:31:13

    你可以b.call(num),一般來說toString不允許作為普通函數執行很容易接受,就跟構造函數一般不作為普通函數執行一樣。
    ps:範例中的Number.prototype.toString()其實作用域也是Number.prototype


    補充一下,答案有點離題了,b()其實是作為函數呼叫的,也呼叫成功了,錯誤是toString()本身拋出的。

    回覆
    0
  • 迷茫

    迷茫2017-06-28 09:31:13

    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 other object. Therefore, it cannot be transferred to other other objects s.

    15.7.4.2 Number.prototype.toString

    回覆
    0
  • 取消回覆