Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I set the 'prototype' of a function created using 'bind'?

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
like image 850
vikrant Avatar asked Feb 23 '19 14:02

vikrant


People also ask

What is prototype bind?

bind() The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

How does bind work in JavaScript?

Summary. The bind() method creates a new function, when invoked, has the this sets to a provided value. The bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.

What is __ proto __ and prototype?

prototype is a property of a Function object. It is the prototype of objects constructed by that function. __proto__ is an internal property of an object, pointing to its prototype.


1 Answers

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)
like image 91
Bergi Avatar answered Sep 28 '22 07:09

Bergi