Javascript 使用';绑定&x27;返回函数时,是否创建闭包?
我的问题涉及以下例子:Javascript 使用';绑定&x27;返回函数时,是否创建闭包?,javascript,closures,bind,Javascript,Closures,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()时,它是否因为bind而在x
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()时,它是否因为bind而在x上有闭包
不完全是
x
的值作为参数传递给bind
考虑一下bind
函数实现的大致近似情况:
function bind(this_value, first_argument_value) {
return function () {
// Call the original function with arguments and context
}
}
Function.prototype.bind = function(context, ...args) {
const bound = this;
return function(...args2) { // the closure
bound.call(context, ...args, ...args2);
};
};
关闭的是第一个参数\u值
,而不是x
调用y()时,它是否因为bind而在x上有闭包
否,对函数调用bind
将返回一个绑定函数。但是,此绑定函数可能会关闭函数和参数,但这取决于实现。带有闭包的实现如下所示:
function bind(this_value, first_argument_value) {
return function () {
// Call the original function with arguments and context
}
}
Function.prototype.bind = function(context, ...args) {
const bound = this;
return function(...args2) { // the closure
bound.call(context, ...args, ...args2);
};
};