簡體   English   中英

javascript OOP從父對象獲取

[英]javascript OOP get from parent object

我該如何訪問子對象的父屬性?

    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'

如何訪問this.obj的子對象?

你不能

有一個baz不管有多少new foo也有,所以沒有辦法從地圖this通常指向單foo.prototype.baz到的特定實例foo

看來您可能打算為foo每個實例創建一個baz

嘗試這個

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

嘗試像這樣定義 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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM