javascript 函数的 bind() 方法

For a given function, creates a bound function that has the same body as the original function. The this object of the bound function is associated with the specified object, and has the specified initial parameters.

function.bind(thisArg[,arg1[,arg2[,argN]]])
传入的第一个参数被赋值给this
thisArg :The value to be passed as the this parameter to the target function when the bound function is called. The value is ignored if the bound function is constructed using the new operator.如果使用new()将忽略这个。

arg1, arg2, ...Arguments to prepend to arguments provided to the bound function when invoking the target function.


return value:
A new function that is the same as the 
function function, except for the thisArg object and the initial arguments.

thisValue:当新的 Function 被调用时,thisValue 会付给其 this 值。如果使用 new 操作符调用 Function,则忽略 thisValue。

arg1, arg2, ...:当新的 Function 被调用时,当作参数列表传入,插入在调用时实际参数之前。

 通过 bind() 修改函数调用时的 this

// 显式作用域
var x = 9,
    module = {
      getX: function() {
        return this.x;
      },
      x: 81
    };

//  调用`module.getX()`,作用域为`module`,所以返回`module.x`
module.getX();
// > 81

//  在全局作用域中保存一个函数的引用
var getX = module.getX;

//  调用`getX()`,作用域为全局,所以返回`x`
getX();
// > 9

//  使用`module` bind作为作用域保存一个引用
var boundGetX = getX.bind(module);

//  调用`boundGetX()`,作用域为`module`,所以返回`module.x`
boundGetX();
// > 81

 

通过 bind() 传入参数

// 创建一个函数,使用预设的开始参数调用另一个函数
function List() {
  var a = [];
  for (var i = 0; i < arguments.length; i++) {
    a.push(arguments[i]);
  }
  return a;
}

//  创建一个 list
var listOne = List(1, 2, 3);

listOne;
// >  [1, 2, 3]

// 创建一个新函数,给定一个预置的参数
var leadingZeroList = List.bind(null /* this */, 0);

leadingZeroList();
// > [0]

leadingZeroList(1);
// > [0, 1]

leadingZeroList(1, 2);
// > [0, 1, 2]

最后,要注意的是:

  • 在使用 new 操作符调用 bind 创建的新函数时,this 不会被修改,但是参数还是会修改;
  • bind 并不被所有浏览器支持,IE 目前不支持。(IE9已经支持)
  • y default within window.setTimeout(), the this keyword will be set to the window (or global) object. When working with class methods that require this to refer to class instances, you may explicitly bind this to the callback function, in order to maintain the instance.
function LateBloomer() {
  this.petalCount = Math.ceil( Math.random() * 12 ) + 1;
}
 
// declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
  window.setTimeout( this.declare.bind( this ), 1000 );
};
 
LateBloomer.prototype.declare = function() {
  console.log('I am a beautiful flower with ' + this.petalCount + ' petals!');
};

从上面的例子中我们可以看出 bind(this);在前,this.declare在后》

看以前写的:javascript 误用this指针 的情况

 http://www.cnblogs.com/rubylouvre/archive/2010/01/05/1639541.html

参考:http://msdn.microsoft.com/en-us/library/ff841995(v=vs.94).aspx

 

原文地址:https://www.cnblogs.com/youxin/p/2697540.html