在闭包内返回函数返回undefined

时间:2013-06-03 03:37:53

标签: javascript function module return closures

我在JavaScript中有一个封闭的函数,如下所示:

var myFunction = function (options) {
    function blah() {
        var blahString = options.blahString;
        //more blah
    }

    function blah2() {
        //blah2
    }

    return {
        blah : function { return blah(); },
        blah2 : function { return blah2(); }
    }
};

当我使用HTML时,我正在尝试拨打myFunction.blah()并告诉我the object has no method 'blah'

如何在全局范围内访问返回的函数?

谢谢!

2 个答案:

答案 0 :(得分:1)

这只是解释了为什么它不起作用以及如何使其工作。为了学习,这就足够了。实际上你应该解释你想要达到的目标,以便其他人可以指导你朝着正确的方向前进。

// A scope of a function is activated ONLY when it is invoked

// Let us define a function
var myFunction = function (options) {
    function blah() {
        alert("I am blah");
    }

    function blah2() {
        //blah2
    }
    alert("I am active now and I am returning an object");
    return {
        blah: function () {
            return blah();
        },
        blah2: function () {
            return blah2();
        }
    };
};

myFunction.blah3 = function () {
    alert("I am blah3");
};

// myFunction is not invoked, but justed used as an identifier. 
// It doesn't have a method blah and gives error
myFunction.blah();

// blah3 is a static method of myFunction and can be accessed direclty using myFunction  
myFunction.blah3();

// myFunction is invoked, which returns an object
// it contains the function blah
myFunction().blah();

// or
var myObject = myFunction();
myObject.blah();
myObject.blah2();

答案 1 :(得分:0)

var myFunction = (function (options) {
  function blah() {
    return options.a;
  }

  function blah2() {
    //blah2
  }

  return {
    blah: function() { return blah(); },
    blah2: function() { return blah2(); }
  };
});

alert(myFunction({a:1, b:2}).blah());

这很好用。注意blah: function< - 需要()

请参阅http://jsfiddle.net/kw6fJ/1

相关问题