Javascript - bind method

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard > Javascript - This

1 - About

The bind method bind the object to the called function.

Creates a new function which, when called, has its this set to the provided value, with a given sequence of arguments preceding any provided when the new function was called.

In non-strict mode, the this of class methods or function is bound by default to their outer scope. In strict mode, the this of class methods or function is bound by default to the inner scope.

Advertising

3 - Example

3.1 - Bind

var x = "globalValue";
var fn = function () {
  return this.x;
};
 
var fnBound = fn.bind( {x: "bindValue"} );
 
console.log( 'fn: ' + fn() ); // GlobalValue
console.log( 'fnBound: ' + fnBound() ); // bindValue

3.2 - Bind and Call

Bind and Call

var boundFn = function () {
  return this.x;
}.bind( {x: 10} );
 
console.log ( 'boundFn: ' + boundFn() ); // 10
console.log ( 'boundFn + call x=20, still 10 : ' + boundFn.call( {x: 20} ) ); // still 10

4 - Documentation / Reference