Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 可以将对象的属性传递给函数,而不使用对象定义的参数';谁的钥匙?_Javascript - Fatal编程技术网

Javascript 可以将对象的属性传递给函数,而不使用对象定义的参数';谁的钥匙?

Javascript 可以将对象的属性传递给函数,而不使用对象定义的参数';谁的钥匙?,javascript,Javascript,快速而奇怪的问题: 我有一个对象(在本例中是小的,但在项目中是大的): 然后我想以某种方式传递给一个函数,并在这样的闭包中使用“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 */)}} }

快速而奇怪的问题:

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

然后我想以某种方式传递给一个函数,并在这样的闭包中使用“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'

在这一切中,
myObject
在哪里?要调用“hey.ya”,您可以调用
myObject['hey.ya']
。您所说的“未定义参数”是什么意思?你的意思是不在函数中定义参数吗?如果你想访问函数中对象的属性作为函数中的变量,你将无法在不预期对象被传递的情况下使用
.eval()
(你不应该这样做)。即使这样,
hey.ya
也不能用作变量标识符。好吧,那似乎是不可能的。。(eval不能使用)是的,您最好只引用作为形式参数传递给函数的对象,并以典型方式访问属性;只要您通过
myObject
标识符访问它,您就不需要传递它。@patrick dw:是的,但我假设他希望能够使用不同的“myObject”值创建多个函数……是的,但是即使您通过
x()
创建多个函数,您仍然通过
myObject
传递相同的对象,因此,它们将共享同一个实例,就像您直接引用它一样。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'