C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript Function bind() methodThe JavaScript Function bind() method is used to create a new function. When a function is called, it has its own this keyword set to the provided value, with a given sequence of arguments. Syntax
function.bind(thisArg [, arg1[, arg2[, ...]]] Parameter
thisArg - The this value passed to the target function. arg1,arg2,....,argn - It represents the arguments for the function. Return Value
It returns the replica of the given function along provided this value and initial arguments. JavaScript Function bind() method ExampleExample 1Let's see a simple example of bind() method.
<script>
var website = {
name: "TheDeveloperBlog",
getName: function() {
return this.name;
}
}
var unboundGetName = website.getName;
var boundGetName = unboundGetName.bind(website);
document.writeln(boundGetName());
</script>
Output: TheDeveloperBlog Example 2Let's see an example of bind() method.
<script>
// Here, this refers to global "window" object
this.name = "Oracle";
var website = {
name: "TheDeveloperBlog",
getName: function() { return this.name; }
};
document.writeln(website.getName()); // TheDeveloperBlog
//It invokes at global scope
var retrieveName = website.getName;
document.writeln(retrieveName()); //Oracle
var boundGetName = retrieveName.bind(website);
document.writeln(boundGetName()); // TheDeveloperBlog
</script>
Output: TheDeveloperBlog Oracle TheDeveloperBlog
Next TopicJavaScript Function
|