19

Consider this code:

function foo(something) {
  this.a = something;
}

var obj1 = {};

var bar = foo.bind(obj1);

Now the following statement doesn't execute:

bar.prototype.newprop = "new"; // Cannot execute this

As I understood, every function has a prototype object. Then why can't we execute the above statement?

And bar is indeed a function as we can call it:

bar(2);
console.log(obj1.a); // 2
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vikrant
  • 2,169
  • 1
  • 21
  • 27

4 Answers4

17

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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Can you tell us, when to use bind method instead of call and apply. – Nithya Rajan Feb 23 '19 at 15:31
  • 2
    @BearNithi uh, they do totally different things? [Javascript call() & apply() vs bind()?](https://stackoverflow.com/q/15455009/1048572) – Bergi Feb 23 '19 at 16:21
4

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 a prototype property.

str
  • 42,689
  • 17
  • 109
  • 127
3

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
2

Adding properties to the prototype means you want to create an object by using the function as a constructor.

When you create an object like by calling new on a function, the this value is the new object being created. So it makes no sense to bind this to another value.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Guerric P
  • 30,447
  • 6
  • 48
  • 86