簡體   English   中英

是否可以將沒有定義參數的對象的屬性傳遞給函數,並通過對象的鍵使用它們?

[英]Is possible to pass to a function the properties of an object without the arguments defined and use them by the object's keys?

快速而奇怪的問題:

我有一個對象(在此示例中較小,但是在項目中較大):

var myObject = {
   hello: 1, // easier I think
   'hey.ya': 5 // quite impossible but the first option is valid too
}

然后我想以某種方式傳遞給函數並在這樣的閉包中使用“ hello”

function x(){
// my closure
   return function(){this.init = function(){alert(hello)}, this.heyYa = function(){alert(/* I do not know how to call the other hey.ya variable */)}}
}

var myClass = x(), instance = new myClass(); instance.init();

謝謝!

您需要使用myObject

var myObject = {
   hello: 1,
   'hey.ya': 5
}

function x(obj){
   return function(){
       this.init = function(){
           alert(obj.hello)
       }, 
       this.heyYa = function(){
           alert(obj['hey.ya'])
       }
   }
}

var myClass = x(myObject);
var instance = new myClass(); 
instance.init(); // alerts '1'
instance.heyYa(); // alerts '5'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM