2013-05-07 63 views
0

我想創建一個類如「MessageBox」。在調用Show()函數時,我將傳遞所需的參數。像:javascript傳遞參數作爲對象或類似

MessageBox.Show(
{ 
    str : "Are you sure?", 
    onYes : function(){ 
    //do something 
    }, 
    onNo: function(){ 
    // Do another stuff 
    } 
}); 

我試了一下:

var MessageBox = { 
    Show : function(){ // I stuck here 
    } 
} 

讓我們展示的JavaScript的功能confirm()被稱爲內假設。

回答

1

應該是這樣的:

var MessageBox = { 
    Show : function(opts){ // I stuck here 
     var result = confirm(opts.str); 
     if (result) { 
     opts.onYes(); 
     } else { 
     opts.onNo(); 
     } 
    } 
} 
+0

謝謝老兄。 – 2013-05-07 09:22:57

1

只是傳遞一個對象作爲參數:

Show: function(obj) { 
    var str = obj.str; 
    ... 
} 
1

你可以只通過它,就像

var MessageBox = { 
    Show : function(params){ // I stuck here 
    console.log(params.str); //would give you "Are you sure?" 
} 
} 
1

嘗試是這樣的:

var MessageBox = function() { 
    var str = 'put your private variables here'; 
}; 

MessageBox.prototype.Show = function(arg) { 
    console.log(arg); 
}; 

var MessageBox = { 
    Show: function(args) { 
     var answer = confirm(args.str); 
     if ((answer) && (typeof args.onYes === "function")) { 
      args.onYes(); 
     } 
     else if (typeof args.onNo === "function") { 
      args.onNo(); 
     } 
    } 
}; 

然後你可以使用它像你想:

0

使得onYes和ONNO功能是可選的,您可以做這樣的事情像下面(包括位檢查

MessageBox.Show({ 
    str: "Are you sure?", 
    onYes: function(){ 
    //do something 
    }, 
    onNo: function(){ 
     // Do another stuff 
    } 
}); 
相關問題