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
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.
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.
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.
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
() => {…}
)method() { … }
in object literals and classes)Math.sin
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With