【问题标题】:Accessing parent objects while using a javascript module pattern variant在使用 javascript 模块模式变体时访问父对象
【发布时间】:2011-11-06 14:34:49
【问题描述】:

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

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

【问题讨论】:

    标签: javascript class object design-patterns parent


    【解决方案1】:

    当您使用 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();
    }
    

    【讨论】:

    • 感谢您的回答,这非常清楚,正是我所追求的。我同意我的示例不需要增加复杂性,我只是尽可能简单地演示模式。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多