0

我在 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'.

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

谢谢!

4

2 回答 2

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();
于 2013-06-03T04:11:39.113 回答
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

于 2013-06-03T03:50:56.983 回答