可以将对象的属性传递给函数,而不需要定义参数,并通过对象的键来使用它们

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

本文关键字:对象 参数 属性 不需要 函数 定义      更新时间:2023-09-26

快速而奇怪的问题:

我有一个对象(在本例中很小,但在项目中较大):

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'