为什么我必须在闭包中定义的闭包访问变量中声明一个函数?

时间:2014-10-12 10:23:37

标签: javascript closures

为什么我必须在闭包中声明一个函数才能访问闭包中的变量?我希望我能够在闭包之外定义函数,但是在它周围闭合,提供它所需的变量,但除非函数实际上是在闭包内定义的,否则变量不可用。

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)();

1 个答案:

答案 0 :(得分:1)

@pherris根据您之前的评论:这无济于事。 IIFE中的this引用window对象,现在您使用其他属性将其垃圾邮件。但myVar and myMethod内的reusableFunction仍未定义,您必须使用this.myVarthis.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); */

})();