JavaScript ООП получить из родительского объекта - PullRequest
0 голосов
/ 22 сентября 2011

Как я могу получить доступ к родительскому атрибуту дочернего объекта, как это?

    var foo = function foo(input){ this.input = input; };
    function bar(input){ return new foo(input); }
    foo.prototype = {
        baz : {
            qux : function(){
                alert(this.parent.input );
            }
        },
        corge : function(){
                alert(this.input );
        }
    }

bar('test').corge(); //alerts 'test'

bar('test').baz.qux(); //errors 'this.parent is undefined'

Ответы [ 2 ]

1 голос
/ 22 сентября 2011

Как я могу получить доступ к this.obj для такого дочернего объекта?

Вы не можете.

Существует один baz независимо от того, сколько их new foo, поэтому нет способа отобразить из this, который обычно указывает на синглтон foo.prototype.baz, конкретный экземпляр foo.

Похоже, вы, вероятно, хотели создать baz для экземпляра foo.

Попробуйте это

function foo(input) {
   this.baz = {
     parent: this,
     qux: quxMethod
   };
   this.input = input;
}
foo.prototype.corge = function () { alert(this.input); };
function quxMethod() {
  alert(this.parent.input);
}
0 голосов
/ 22 сентября 2011

Попробуйте определить baz примерно так:

  baz : (function(){
        var parent = this;
        return {
           qux : function(){
               alert(parent.obj);
           }
        }
    })()


Обновление:

Я верю, что это сделает то, что вы хотите:
Демо: http://jsfiddle.net/maniator/rKcwP/
Код:

var foo = function foo(input) {
    this.input = input;
};

function bar(input) {
    return new foo(input);
}
foo.prototype = {
    baz: function() {
        var parent = this;
        return {
            qux: function() {
                alert(parent.input);
            }
        }
    },
    corge: function() {
        alert(this.input);
    }
}

bar('test').corge(); //alerts 'test'
bar('test').baz().qux(); //alerts 'test'
...