Dan*_*mov 22 javascript bind function ecmascript-5
我正在考虑使用currying和其他技术Function.prototype.bind.在某些情况下
改变功能范围(即this值)似乎非常有用.
function f = obj.method.bind(42);
function g = obj.method.bind('Hi');
function f2 = f.bind('Hi'); // “this” is still 42
Run Code Online (Sandbox Code Playgroud)
是否可以从绑定函数中检索原始的未绑定函数?
Win*_*n32 26
该bind方法基本上是做什么的(不完全是,因为参数被切片以排除上下文):
function bind(context) {
var self = this;
return function() {
self.apply(context, arguments);
}
}
Run Code Online (Sandbox Code Playgroud)
所以基本上它返回另一个函数,它将使用给定的上下文和参数调用自身.如果你再次使用bind它,你将绑定这个新创建的函数,就好像bind是这样实现的:
function bind(context) {
var self = this;
return function() {
self.apply(context, arguments);
}.bind(otherContext);
}
Run Code Online (Sandbox Code Playgroud)
但是因为bind返回的内部函数充当了一个闭包,其中原始上下文是绑定的第一个(self),那个将成为你的函数的上下文将被真正执行.