search

Home  >  Q&A  >  body text

es6 numerical destructuring Number.prototype.toString is not generic - es6 numerical destructuring 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>

Why can't b be called as a function?

扔个三星炸死你扔个三星炸死你2817 days ago903

reply all(3)I'll reply

  • 滿天的星座

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

    Number.prototype.toString standard

    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.

    Translate the following:

    If its this value is not a numeric type or a Number object, a TypeError

    will be thrown

    Directly call this is window
    You can use it like this:

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

    reply
    0
  • 过去多啦不再A梦

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

    You can b.call(num), and generally speaking, it is easy to accept that toString is not allowed to be executed as an ordinary function, just like constructors are generally not executed as ordinary functions.
    ps: The Number.prototype.toString() in the example actually has the same scope as Number.prototype


    To add, the answer is a bit off topic. b() is actually called as a function and the call is successful. The error is thrown by toString() itself.

    reply
    0
  • 迷茫

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

    Number.prototype.toString can be called as a function but this must be of type Number. The same applies to other types of 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

    reply
    0
  • Cancelreply