![](/img/trans.png)
[英]How can I access variables in a closure from inside of a function in that closure?
[英]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根據您之前的評論:這無濟於事。 在this
的IIFEs內指的是window
對象,現在你有附加屬性的垃圾郵件了。 但是reusableFunction
myVar and myMethod
仍未定義,您必須改用this.myVar
和this.myMethod
。 比向窗口發送垃圾更好的是將vars作為參數傳遞:
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); */
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.