为什么我必须在闭包中声明一个函数来访问闭包中定义的变量
Why do I have to declare a function within a closure access variables defined in the closure?
为什么我必须在闭包中声明一个函数才能访问闭包中的变量?我希望我能够在闭包之外定义函数,但在闭包周围闭合,提供所需的变量,但除非函数实际上在闭包中定义,否则这些变量是不可用的。
http://jsfiddle.net/c5oba93a/1/
//reusable function defined outside of closure, I want to swap out myMethod within this function.
var reusableFunction = function () {
//common code
try {
console.log(myVar);
myMethod.call(this);
} catch (e) {
console.log(e);
}
//common code
};
var functOneForClosure = function () {
console.log('functOne');
};
var functTwoForClosure = function () {
console.log('functTwo');
};
//myMethod and myVar are undefined in reusableFunction
(function () {
var myMethod = functOneForClosure;
var myVar = 'variable in closure with functOne';
return reusableFunction;
})()();
(function (myMethodIn) {
var myMethod = myMethodIn;
var myVar = 'variable in closure with functTwo';
return reusableFunction;
})(functOneForClosure)();
//if the function is defined within the closure it behaves as expected.
var getReusableVersion =(function (myMethod) {
var myVar = 'defining function within closure makes the difference';
return function () {
//common code
try {
console.log(myVar);
myMethod.call(this);
} catch (e) {
console.log(e);
}
//common code
};
});
getReusableVersion(functOneForClosure)();
@pherris根据你的beforelast评论:那没用。IIFE中的this
引用了window
对象,现在您可以使用其他属性对其进行垃圾邮件处理。但是reusableFunction
中的myVar and myMethod
仍然未定义,您必须使用this.myVar
和this.myMethod
。比垃圾邮件窗口更好的是将变量作为参数传递:
var reusableFunction = function (myVar, myMethod) {
// no try/catch needed anymore
console.log(myVar);
if (typeof myMethod == 'function') myMethod.call(this);
else console.log(myMethod);
};
现在有两种方法可以用IIFE调用它。
第一个从IIFE返回函数,并将参数绑定到它,然后执行它:
(function () {
var myMethod = functOneForClosure;
var myVar = 'variable in closure with functOne';
// first argument of .bind() appears in the function as 'this',
// the others appear as fixed arguments of the function
return reusableFunction.bind(window, myVar, myMethod);
})()();
第二种方法在IIFE内部调用它,因此之后的调用被删除:
(function () {
var myMethod = functOneForClosure;
var myVar = 'variable in closure with functOne';
return reusableFunction(myVar, myMethod);
// of course its possible to call on 'this', but that doesn't change anything:
/* return reusableFunction.call(this, myVar, myMethod); */
})();
相关文章:
- 使用闭包/函数绑定将自函数作为回调传递
- 了解 JavaScript 闭包函数
- 传递多个参数的闭包函数
- 将“(0)”附加到此闭包函数的目的是什么
- 如何复制(新实例)闭包函数
- Javascript 闭包函数参数
- 具有闭包函数作用域的意外行为
- javascript闭包函数可以由用户更改吗
- Javascript:是这个闭包函数
- 为什么闭包函数中的 javascript 变量在多次调用时不会重置为默认值
- Js闭包:函数在第二次调用时失败
- 如何存储闭包函数返回的变量
- javascript闭包函数的用法
- JavaScript闭包函数传递给事件监听器
- 闭包函数问题
- & # 39;这个# 39;匿名闭包函数内部
- 在JavaScript中实现自动记忆(返回闭包函数)
- 不理解闭包函数是如何工作的
- Javascript闭包函数
- 为javascript闭包函数编写jasmine测试规范