Javascript-Function Binding
The JavaScript Function bind() method is provided to create a new function. When a function is called, it has its own this keyword(this keyword refers to the same object which is currently selected) set to the provided value, with a given sequence of arguments.
Syntax:
function.bind(thisArg [, arg1[, arg2[, ...]]]
Example:
print the name which is return by this keyword when the function printFunc() is invoked.
<script>
var tutorial= {
name : "ABC",
printFunc: function(){
document.write(this.name);}
}
tutorial.printFunc();
</script>
OUTPUT:
ABC
Parameter:
- thisArg – This value passed to the target function.
- arg1,arg2,….,argn – The arguments for the function.
JavaScript Function bind():
<!DOCTYPE html>
<html>
<body>
<script>
var website = {
name: "I2tutorials",
getName: function() {
return this.name;
}
}
var unboundGetName = website.getName;
var boundGetName = unboundGetName.bind(website);
document.writeln(boundGetName());
</script>
</body>
</html>
OUTPUT:
I2tutorials
Example :
bind() method.
<!DOCTYPE html>
<html>
<body>
<script>
// Here, this refers to global "window" object
this.name = "Oracle";
var website = {
name: "I2tutorials",
getName: function() { return this.name; }
};
document.writeln(website.getName()); // Javatpoint
//It invokes at global scope
var retrieveName = website.getName;
document.writeln(retrieveName()); //Oracle
var boundGetName = retrieveName.bind(website);
document.writeln(boundGetName()); // Javatpoint
</script>
</body>
</html>
OUTPUT:
I2tutorials Oracle I2tutorials