function:
function talk(){
console.log(this.name + " dice: ");
}
var Person = function(name, surname){
this.name = name;
this.surname = surname;
}
var p = new Person("Mark", "Red");
talk.bind(p);
what's wrong with bind?
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.
. bind() is used when you need to pass a callback (e.g. some sort of function reference), but you want the caller to call your function with a specific this value.
We use the Bind() method to call a function with the this value, this keyword refers to the same object which is currently selected . In other words, bind() method allows us to easily set which object will be bound by the this keyword when a function or method is invoked.
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.
Description. The bind () function creates a new bound function, which is an exotic function object (a term from ECMAScript 2015) that wraps the original function object. Calling the bound function generally results in the execution of its wrapped function. A bound function has the following internal properties:
In this syntax, the bind () method returns a copy of the function fn with the specific this value ( thisArg) and arguments ( arg1, arg2, …). Unlike the call () and apply () methods, the bind () method doesn’t immediately execute the function. It just returns a new version of the function whose this sets to thisArg argument.
If no arguments are provided to bind , or if the thisArg is null or undefined, the this of the executing scope is treated as the thisArg for the new function. Arguments to prepend to arguments provided to the bound function when invoking func . A copy of the given function with the specified this value, and initial arguments (if provided).
We’ve created a new function that, when executed, has its this set to foo — not the global scope, as in the example where we called bar ();. As you can see, unfortunately, Function.prototype.bind isn’t supported in Internet Explorer 8 and below, so you’ll run into problems if you try to use it without a fallback.
It does work, talk.bind(p) returns the bound function:
talk.bind(p)();
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