我正在尝试从JavaScript中的其他函数中访问设置和值/函数,并且相信可能存在一个我缺少的简单规则。这是一个非常简化的代码示例:
function h(){
// example settings I want to declare for h()
this.settings = {
critical: 400,
readCritical: function(){
return this.settings.critical; // /!\ but this does not work
}
}
this.hsub = function(){
return this.settings.critical; // /!\ this does not work either
}
}
var x = new h();
console.log(x.settings.critical); // This works fine
console.log(x.settings.readCritical()); // I can *call* this fine, but it can't read outside itself
console.log(x.hsub()); // I can also call this but same problem
console.log(h.settings); // `undefined`; I understand I can't see directly into the function
您可以在相应的功能this.settings.critical
和readCritical
中看到我要尝试访问的hsub
值。我怎样才能做到这一点?特别是来自实例化的x
。
同样是次要问题但相关,我更愿意声明var settings = {}
而不是this.settings
。这是可能的还是更可取的?
答案 0 :(得分:2)
只需更改即可从.settings
功能中删除readCritical
。
hsub
按原样运作。不确定为什么你认为有问题
function h(){
this.settings = {
critical: 400,
readCritical: function(){
return this.critical; // reference `critical` directly
}
}
this.hsub = function(){
return this.settings.critical; // this works just fine
}
}
var x = new h();
console.log(x.settings.critical); // 400
console.log(x.settings.readCritical()); // 400
console.log(x.hsub()); // 400
// This is expected to be `undefined`
console.log(h.settings);

答案 1 :(得分:1)
啊,另一个古老的经典封闭问题。
有两种方法可以解决它:
function h(){
var self = this;
this.settings = {
critical: 400;
readCritical: function() {
return self.settings.critical(); // otherwise this.settings will 'cover' `this`.
}
}
}
readCritical: () => this.settings.critical(); // arrow functions won't form a function scope
答案 2 :(得分:1)
this
的范围(以及设置它的绑定函数)是JS中讨论很多的主题。但是,您似乎并不是专门寻找this
,而是共享变量,还有其他选择。总而言之,没有最佳答案,但由于您还要声明var settings = {}
:您实际上可以并且可以访问其他函数中可用的局部变量。
function h(){
var settings = { //var settings is a local variable of the function h (or instance of it). If ES6 is allowed 'let' or 'const' are preferrable
critical: 400,
readCritical: function(){
return settings.critical;
}
};
this.settings = settings; //this.settings is not the same variable as var settings, making this statement valid
this.hsub = function(){
return settings.critical; //the local (var) settings is used
}
}
var x = new h();
console.log(x.settings.critical);
console.log(x.settings.readCritical());
console.log(x.hsub());

这里的陷阱是,如果调用代码将x.settings
更改为其他内容,则变量将不会指向同一个实例(如果它们更改了x.settings
内的值,一切都很好)。如果这是一个风险,它可以作为属性方法公开
答案 3 :(得分:1)
看起来你只想拥有一个实例。如果是这样,那么只需使用对象文字表示法立即创建实例:
var h = {
settings: {
critical: 400,
readCritical: function(){
return this.critical;
}
},
hsub: function(){
return this.settings.critical;
}
}
console.log(h.settings.critical);
console.log(h.settings.readCritical());
console.log(h.hsub());
console.log(h.settings);

现在,在给定单例对象h
时,所有四个属性访问都按预期工作。