javascript 函数的 bind() 方法
2012-09-21 22:05 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()
, thethis
keyword will be set to thewindow
(orglobal
) object. When working with class methods that requirethis
to refer to class instances, you may explicitly bindthis
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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步