Why can't I set the 'prototype' of a function created using 'bind'?
As I understood, every function has a prototype object.
Well, there are exceptions to every rule :-) You found one: bound functions don't have a .prototype
property because they don't need it. When you call a bound function with new
, it calls the original function as a constructor, using the original's .prototype
object as the prototype of the new instance.
In fact, since ECMAScript 6 many functions don't have a .prototype
property with an object, because they are not constructors - they cannot be called with new
so they don't need it. Among those are
- arrow functions (
() => {…}
) - methods (
method() { … }
in object literals and classes) - builtin non-constructor functions (like
Math.sin
)
See the specification:
Function.prototype.bind ( thisArg , ...args)
[...]
NOTE 1 Function objects created using
Function.prototype.bind
are exotic objects. They also do not have aprototype
property.
The returned function from .bind()
has no prototype object. You can give it one:
bar.prototype = { newprop: "new" };
It is not true that "every function has a prototype object". Every function can have a prototype object, but the value of the "prototype" property can be anything, including null
or undefined
.
Additionally, there are "special" functions that may not behave like ordinary functions in all cases.