<!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?
滿天的星座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:
will be thrownIf its
this
value is not a numeric type or aNumber
object, aTypeError
Directly call this
is window
You can use it like this:
b.call(1)
b.call(Number('test'))
过去多啦不再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.
迷茫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