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