返回函数时使用'bind'会创建闭包吗?



我的问题与以下示例有关:

function inner(x){
return x;
}
function outer(fn){
var x = 'I just made a closure!!!'
return  fn.bind(this, x)
}
var y = outer(inner)
y()

当调用y()时,它是否因为bind而关闭了x?我很困惑,因为它确实可以访问函数outer的内部变量,但它仍然声明在outer范围之外

当调用

y() 时,它是否因为绑定而在 x 上闭包?

否,对函数调用bind会返回绑定函数。但是,此绑定函数可能会关闭函数和参数,但这取决于实现。带有闭包的实现如下所示:

Function.prototype.bind = function(context, ...args) {
const bound = this;
return function(...args2) { // the closure
bound.call(context, ...args, ...args2);
};
};
当调用

y() 时,它是否因为绑定而在 x 上闭包?

差一点。

x的值作为参数传递给bind

考虑一下bind函数实现的粗略近似值:

function bind(this_value, first_argument_value) {
return function () {
// Call the original function with arguments and context
}
}

关闭的是first_argument_value,而不是x.

最新更新