使用javascript模块模式变体时访问父对象

时间:2011-11-06 14:34:50

标签: javascript class object design-patterns parent

您好我正在使用此模块模式变体,我正在寻找访问父对象的最佳方法。我意识到没有办法知道对象的父对象有什么,所以我想在构造函数中包含一些上下文。我认为这会有效,但它没有,任何想法?

$(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

1 个答案:

答案 0 :(得分:2)

使用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)。在你的情况下,也许你可以通过“少OO”方法逃脱?

//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();
}