使用 javascript 模块模式变体时访问父对象
您好,我正在使用此模块模式变体,我正在寻找访问父对象的最佳方法。我意识到无法知道对象有哪些父对象,因此我想在构造函数中包含一些上下文。我以为这会起作用,但事实并非如此,有什么想法吗?
$(document).ready(function(){
var main = new Main();
});
function Main() {
var one = 'hello';
init();
function init() {
var data = new Data(this);
var two = data.load();
console.log(one+' '+two);
data.output();
}
}
function Data(context) {
// public vars / methods
var pub = {
'load' : function() {
return ('world');
},
'output' : function() {
var one = context.one // <-- what should this be?
var two = this.load();
console.log (one+' '+two);
}
}
return pub;
}
输出是:
hello world
undefined world
Hi I'm using this module pattern variant and I'm looking for the best way to get access to a parent object. I realise there is no way to know what parents an object has so I want to include some context in the constructor. I thought this would work but it doesn't, any ideas?
$(document).ready(function(){
var main = new Main();
});
function Main() {
var one = 'hello';
init();
function init() {
var data = new Data(this);
var two = data.load();
console.log(one+' '+two);
data.output();
}
}
function Data(context) {
// public vars / methods
var pub = {
'load' : function() {
return ('world');
},
'output' : function() {
var one = context.one // <-- what should this be?
var two = this.load();
console.log (one+' '+two);
}
}
return pub;
}
The output is:
hello world
undefined world
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您使用 new 运算符调用构造函数时,您基本上会执行类似
当您使用 var 声明私有变量时它将只是一个普通变量而没有其他内容。如果您想向
this
添加内容,您需要明确地这样做,但这还不是全部!
this
没有词法作用域,因此 init 函数会从外部获取与this
无关的其他this
(这解释了你得到的undefined
)。当您想在内部函数中使用this
时,您需要采取解决方法,例如:也就是说,仅通过您的示例,我不明白为什么您需要执行所有这些操作。我更喜欢仅在绝对必要时(当我想使用原型继承时)才使用构造函数(和
new
)。在你的情况下,也许你可以采用“更少的面向对象”方法?When you call a constructor function with the
new
operator, you are basically doing something likeWhen you declare a private variable with
var
it will just be a plain variable and nothing else. If you want to add things to thethis
you need to do so explicitelyBut that is not all!
this
is not lexically scoped so the init function gets its own otherthis
that is unrelated to thethis
from outside (this explains theundefined
you get). When you want to usethis
in an inner function you need to do a workaround, like in:That said, just by your example I don't see why you need to do all of this. I prefer to use constructor functions (and
new
) only when strictly necessary (when I want to make use of prototypal inheritance). In your case perhaps you can get away with a "less OO" approach?