代码改变世界

javascript 函数的 bind() 方法

  youxin  阅读(606)  评论(0编辑  收藏  举报

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.

thisArg :
this
new
arg1, arg2, ...

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

 

努力加载评论中...
点击右上角即可分享
微信分享提示