bind Method (JavaScript)
Creates a function that is associated with a specified object, and that can have specific initial parameters.
functionname.bind(thisArg[,arg1[,arg2[,argN]]])
The following example illustrates the use of the bind method.
// Define the original function. function showBind1() { var checkNumericRange = function (value) { if (typeof value !== 'number') return false; else return value >= this.minimum && value <= this.maximum; } // The objForThis argument enables use of the this value // within the callback function. var objForThis = { minimum: 10, maximum: 20 }; // Create a new function that binds objForThis to // the checkNumericRange function. var chk = checkNumericRange.bind(objForThis); // Use the new function to check whether 12 is in the numeric range. var result = chk(12); document.write(result); // Output: true }
In the following example, the object referred to by the this keyword is different from the object that contains the original function.
function showBind2() { // Create an object that contains the original function. var objWithProps = { minimum: 50, maximum: 100, checkNumericRange: function (value) { if (typeof value !== 'number') return false; else return value >= this.minimum && value <= this.maximum; } } // Check whether 10 is in the numeric range. var result = objWithProps.checkNumericRange(10); document.write(result + " "); // Output: false var objForThis = { minimum: 10, maximum: 20 }; // Create a new version of the checkNumericRange function. // For the new function, the object referred to by the // this keyword is different from the object that contains // the original function. var chk = objWithProps.checkNumericRange.bind(objForThis); // Using the new function, check whether 10 is in the numeric // range. var result = chk(10); document.write(result); // Output: true }
In the following example, the bind method call includes arg1[,arg2[,argN]]] arguments. When the new function is called, these values are provided as the initial arguments.
function showBind3() { // Define the original function. var displayArgs = function (val1, val2, val3, val4) { document.write(val1 + " " + val2 + " " + val3 + " " + val4); } var objForThis = {}; // Create a new function that is the same as the // original function, except that the 12 and "a" parameters // are always the first two parameters. var displayArgs2 = displayArgs.bind(objForThis, 12, "a"); // Call the new function. displayArgs2("b", "c"); // Output: 12 a b c }
Supported in the Internet Explorer 9 standards document mode. See Version Information.
Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards.