在使用javascript模块模式变体时访问父对象
Accessing parent objects while using a javascript module pattern variant
嗨,我正在使用这个模块模式变体,我正在寻找访问父对象的最佳方法。我意识到没有办法知道一个对象有什么父母,所以我想在构造函数中包含一些上下文。我以为这能行,但是不行,有什么主意吗?
$(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
当您使用new
操作符调用构造函数时,您基本上是在做类似
function Main(){
var this = //magic new object
//provided by the runtime
//your code comes here
return this;
//because your Data function returns a value,
// you never get to this line. Perhaps you should use
// a regular non-constructor data() function instead?
}
当您使用var
声明私有变量时,它将只是一个普通变量,没有其他内容。如果你想添加东西到this
,你需要这样做显式
this.one = 'hello';
但这还不是全部!this
不是词法作用域,因此init函数从外部获得与this
无关的其他this
(这解释了您获得的undefined
)。当你想在内部函数中使用this
时,你需要做一个变通的方法,比如:
var that = this;
function init(){
new Data(that);
}
init();
也就是说,仅凭你的例子,我不明白为什么你需要做所有这些。我更喜欢只在严格必要时(当我想使用原型继承时)才使用构造函数(和new
)。在您的情况下,也许您可以使用"少面向对象"的方法?
//main doesn't need to be a class
// this is not Java :)
function main(){
//just a plain object for the
//context. Create a separate class
//if you really need to...
var context = {
one: 'hello'
};
var data = new Data(context);
var two = data.load();
console.log(one+' '+two);
data.output();
}
相关文章:
- 如何访问对象内部的“categoryIds”字段/键,该对象包含mongodb's `ObjectId(s)`数
- 使用js或extjs访问对象的java列表
- Javascript-访问对象
- 访问对象的最简单方法'的单独财产
- 分析云代码访问对象
- 如何从字符串变量访问对象属性
- 访问对象中的数组
- 如何访问对象's成员通过另一种方法填充的方法
- 访问对象内的数组
- 是否可以在定义对象时访问对象值
- Javascript 无法访问对象的属性
- $.each 中的“this”,当需要使用“this”访问对象的函数时
- 函数中的 angularJS 访问对象属性不起作用
- 通过存储在变量中的名称访问对象
- 访问对象内部的数组
- 如何从类函数内部访问对象属性
- 访问对象和指定变量
- Javascript - 使用 for 时遇到问题.以循环访问对象
- 为什么可以在内部函数成员中访问对象引用,而不能在内部属性成员中访问
- 当对象的键中有冒号时,如何访问对象属性