问题描述
在使用 javascript 对象时,我找到了这段代码:
While working with javascript object I came to this code :
var mainModule = {
opt : {
opt1: 'my option1',
opt2: 'my option2',
opt3: 'my option3',
},
init: function(options){
jQuery.extend(this.opt, options);
this.mainMethod();
},
mainMethod: function() {
//do Stuff
var color = this.opt.opt1;
},
secondaryMethod1: function(){/*stuff*/},
secondaryMethod2: function(){/*stuff*/},
secondaryMethod3: function(){/*stuff*/},
secondaryMethod4: function(){/*stuff*/},
thirdlyMethod1: function(){/*stuff*/},
thirdlyMethod2: function(){/*stuff*/},
thirdlyMethod3: function(){/*stuff*/},
thirdlyMethod4: function(){/*stuff*/},
};
使用此代码,我经常使用 this.opt
检查 opt 对象,因为 this
是 mainModule.但是所有的代码开始变得一团糟,使用所有不同的方法所以我以这个新代码结束,在主要对象中增加了一个新的深度.
With this code I often check the opt object with this.opt
as this
is mainModule.But all the code begin to be a littre messy with all the different methodso I ended with this new code whith a new level of depth in the main object.
var mainModule = {
opt : {
opt1: 'my option1',
opt2: 'my option2',
opt3: 'my option3',
},
init: function(options){
jQuery.extend(this.opt, options);
this.mainMethod.init();
},
mainMethod: {
init: function() {
//do Stuff
var color = mainModule.opt.opt1;
},
other: function(){},
functions: function(){},
here: function() {}
},
secondary: {
method1: function(){/*stuff*/},
method2: function(){/*stuff*/},
method3: function(){/*stuff*/},
method4: function(){/*stuff*/},
}
thirdly: {
Method1: function(){/*stuff*/},
Method2: function(){/*stuff*/},
Method3: function(){/*stuff*/},
Method4: function(){/*stuff*/},
}
};
但是有了这个新的,我不能使用 this.opt
因为 this
不再是 mainModule.
But with this new one I can't use this.opt
because this
isn't the mainModule anymore.
对于这种对象,有没有更好的方法来检索 opt 对象?这种新的深度水平是必要的还是应该使用伪命名空间?
With this kind of object, is there a better way to retrieve the opt object ?Does this new level of depth is necessary or should I use maybe a pseudo namespace ?
推荐答案
您始终可以在 IIFE 中设置主模块,并将选项作为局部变量存储在该函数中.看起来像这样:
You could always set up the main module in an IIFE and store the options as a local variable in that function. Which looks like this:
var mainModule = (function() {
// Keep the options out of the object that's returned.
// Hides the options to stop things like mainModule.options.opt1 = 'EVIL';
var opt = {};
return {
init: function(options){
jQuery.extend(opt, options);
this.mainMethod.init();
},
mainMethod: {
init: function() {
console.log(opt);
},
other: function(){},
functions: function(){},
here: function() {}
},
secondary: {
method1: function(){},
method2: function(){},
method3: function(){},
method4: function(){},
},
thirdly: {
Method1: function(){},
Method2: function(){},
Method3: function(){},
Method4: function(){},
}
};
}());
现在你所有的函数都可以只引用opt
——你甚至不再需要this
.
Now all your functions can just reference opt
- you don't even need this
anymore.
这篇关于从作为子对象方法的函数中引用主 JavaScript 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!