簡體   English   中英

Javascript:從嵌套類訪問超類對象

[英]Javascript: Accessing superclass objects from nested class

a = new function() {
    this.x=2;
    B=function() {
        this.y=super.x;
    }
    this.b=new B();
}

alert(a.b.y); // Expecting 2

在上面,在super存在解析錯誤。 定義類B時如何訪問x的值?

這有效,但我不確定您的代碼是否正確

a = new function() {
    var x=2;
    B=function() {
        this.y=x;
    }
    this.b=new B();
}

alert(a.b.y); //alerts 2
alert(a.x) //alert undefined becuase x is private

無論如何,在javascript中都沒有super ,如果您在這里閱讀可以看到如何通過uber方法在javascript中實現慣性

發現執行此操作的最佳方法是在嵌套類的構造函數中將“ this”作為參數傳遞,如下所示:

a = new function() {
    this.x=2;
    B=function(sup) {
        this.y=sup.x;
    }
    this.b=new B(this);
}

alert(a.b.y); // Displays 2

暫無
暫無

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

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