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

Accessing parent objects while using a javascript module pattern variant

本文关键字:访问 对象 模式 javascript 模块      更新时间:2023-09-26

嗨,我正在使用这个模块模式变体,我正在寻找访问父对象的最佳方法。我意识到没有办法知道一个对象有什么父母,所以我想在构造函数中包含一些上下文。我以为这能行,但是不行,有什么主意吗?

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