如何将setTimeout()与Singleton Module Pattern一起使用?

时间:2010-11-03 12:05:42

标签: javascript

公共方法想要在一段时间后调用私有方法(将一些对象作为参数传递)...我们如何做?

想要这样的事情:

var someClass = function(someObj) {
    var myPrivateMethod = function(someParam) {
        alert('i got ' + someObj + '!');
        if (someParam) alert('and i also got ' + someParam + '!');
    }

    var myDearPublicMethod = function(someParam) {
        if (someParam) {
            //call myPrivateMethod with setTimeOut so that it gets the someObj (and someParam if provided)
        } else {
            myPrivateMethod(someParam);
        }
    }

    return {
        somePublicMethod : myDearPublicMethod
    }
}

someClass('something').somePublicMethod('somethingELSE');

2 个答案:

答案 0 :(得分:2)

调用一个调用函数的匿名函数:

window.setTimeout(function(){
  localFunction(someObject);
}, 1000);

答案 1 :(得分:0)

目前尚不清楚你的目标是什么

if (someParam) {
            //call myPrivateMethod with setTimeOut so that it gets both someObj and someParam
        } else {
            myPrivateMethod(someParam);
        }

为什么在else分支中调用someParam作为参数的方法,如果在那个分支中你刚刚验证someParam是false,null还是undefined?分支之间真正的区别是什么?