我喜欢使用对象文字来编写Javascript。我经常需要设置一些将在我的应用程序中使用的变量,但我总是很难知道如何制作这些变量:
这是一个简化的例子。真的只是想说明这一点。在编写具有许多不同功能的大型应用程序时,这一点变得更加重要:
var Application={
establishVars: function(){
var importantObject ={
type: 'awesome_object',
value: '1000'
}
return importantObject
},
process: function(){
//I need importantObject here
var neededVar = Application.establishVars(),
modifiedValue = neededVar['value'] - 500;
modifiedVar = {
type: 'really bad object',
value: modifiedValue
}
Application.output(modifiedVar);
},
output: function(e){
//I also need importantObject here!
var neededVarAgain = Application.establishVars();
console.log('you should have just stuck with ' + neededVarAgain['type'] + ' it had a value of ' + neededVarAgain['value'] );
console.log('its much better than the ' + e['value'] + ' provided by ' + e['type'] );
}
}
我意识到的一个选择是我可以通过链条抛出我需要的变量,如足球:
var Application={
establishVars: function(){
var importantObject ={
type: 'awesome_object',
value: '1000'
}
return importantObject
},
process: function(){
//I need importantObject here
var neededVar = Application.establishVars(),
modifiedValue = neededVar['value'] - 500;
modifiedVar = {
type: 'really bad object',
value: modifiedValue
}
Application.output(modifiedVar, neededVar);
},
output: function(mod, orig){
//I also need importantObject here!
console.log('you should have just stuck with ' + orig['type'] + ' it had a value of ' + orig['value'] );
console.log('its much better than the ' + mod['value'] + ' provided by ' + mod['type'] );
}
}
$(document).ready(Application.process);
对于像这个例子一样小的东西,这两种方法都可以正常工作。但是,出于问题的目的,在更大的应用程序中,快速轻松地将许多变量用于许多函数的最佳方法是什么?如果我们需要将重要对象转换为五个或六个不同的函数,该怎么办?我觉得有一种更好的方法,而不仅仅是让一个功能专门用于返回我需要的变量。