JavaScript作用域问题求助

3

我今天可能有点糊涂了,因为我不知道如何做我想要的事情。我想要一个自定义提示框,可以从我的其他JavaScript函数中调用它。尽管我觉得我已经做了一百次,但我还是不知道如何使其工作。

下面是一个例子:

var modal = function() {

    var prompt = function(msg) {
        // custom prompt builder here... let's return hard coded for example's sake
        return true;
    };

}();

var items = function() {
    var init = function() {

        $('.delete').click(function() {
            var confirm = modal.prompt('Are you sure you wanna delete that pal?');
        });

    };    


    $(document).ready(init);    
}();

我想要做的是调用模态框的提示方法,并根据用户输入获得返回值。这个我能做到,但我在调用内部方法时遇到了问题。我想把它们分组在一起,因为我可能也会有一个自定义的alert()模态框。
请不要建议使用内置的JavaScript OK/Cancel,因为我必须自定义。
非常感谢!

2
附注:如果您立即调用匿名函数,最好将函数括在括号中。这使得调用更加显眼。如果您不这样做,有人可能会忽略尾随的 () 并误解您的意图。 - outis
@otis 你的意思是在外面再加一对括号吗?我好像以前见过这种写法。谢谢你的提示。 - alex
无论如何,您都无法根据用户输入获取返回值,因为脚本将在用户交互出现之前完全执行(包括return语句)。您必须使用不同的流程来依赖回调函数。您将无法模仿prompt的本机行为。 - David Hedlund
4个回答

4

从你调用 modal.prompt 的方式来看,似乎你想让匿名函数返回一个对象,并将其存储在 modal 中:

var modal = (function() {
    // various private fields & methods here
    ...
    // the public interface
    var self = {
        prompt: function(msg) {
            // custom prompt builder here... let's return hard coded for example's sake
            return true;
        }
    };
    return self;
})();

3

对于你的第一个问题,prompt函数被声明为modal对象内的变量,你无法访问它,因为它实际上并没有公开暴露出来:

var modal = (function() {
  var privateMethod1 = function () {/*...*/},
      privateVar = 'foo';

  function privateMethod2() {
    //...
  }

  return { // public members
    prompt: function (msg) {
      // custom prompt builder here... let's return hard coded for example's sake
      return true;
    }
  };
})();

现在来看以下问题:

我想要做的是调用 modal 的 prompt 方法,并根据用户输入获取返回值。

用户输入是一个异步操作,我建议您使用基于回调的模型,内置的 JavaScript OK/Cancel window.prompt 实际上可以返回一个值,因为它停止代码执行并等待用户输入。

var modal = (function() {
    return {
      prompt: function(msg, okCallback, cancelCallback) {
        // ...

        $('#okButton').click(function () {
          // internal actions here, like closing the dialog, cleanup, etc...
          okCallback(); // execute the ok callback
        });

        $('#cancelButton').click(function () {
          // ...
          cancelCallback(); // execute the cancel callback
        });
      }
    };
})();

2

+1 Alex可能会将闭包与属性混淆,但这是一份非常好的文档。 - outis
该文档不仅涵盖了闭包,还详细介绍了作用域。 - Jotham

0

你尝试过了吗:

var modal = {
    prompt : function(msg) {
           return true;
         }
};

然后你可以像这样调用它:

modal.prompt();

我想你的意思是建议: var modal = { prompt: function(msg) {return true;} }; - Bruce

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接