javascript OOP来自父对象

时间:2011-09-21 20:17:59

标签: javascript oop parent

如何访问像这样的子对象的父属性?

    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 个答案:

答案 0 :(得分:1)

  

如何为这样的子对象访问this.obj

你不能。

有一个baz,无论有多少new foo,因此无法从通常指向单身this的{​​{1}}映射到特定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);
}

答案 1 :(得分:0)

<击> 尝试定义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'