簡體   English   中英

從另一個文件訪問相同的 Javascript 類實例

[英]Accessing same instance of Javascript class from another file

所以我有這個 JavaScript 類“Test”。 我想在 Main react 組件中創建它的實例,然后在另一個由某些操作調用的 react 組件中使用相同的實例。

class Test
    {
        constructor( arg1, arg2 )
        {
            console.log("initialize with " + arg1 + arg2);
    }
        
        method1(input) {
            console.log("Using this in Main component")
        }

        method2(input) {
            console.log("I want to use this in another component but with same instance as Main component is using.")
        }
    
    }
    export default Test;

這是我創建測試實例的主要組件的開始

class Main extends React.Component
{
    constructor(props)
    {
        super(props);
        new Test("arg1", "arg2")
            .then(test => {
                test.method1("input");
            });
    }

現在我想使用我在下面創建的相同的 Test 實例,但這次使用method2

    export default class AccessFromhere extends React.Component {
        constructor()
        {
            super();
            this.access = this.access.bind(this);
        }
        access()
        {
            console.log("How to get same instance of Test from here to use method2 instead.")
  new Test("arg1", "arg2")
                .then(test => {
                    test.method2("input");
                });
        }

我通過創建新的 Test 實例來做到這一點,但感覺這不是一個好方法。

當您從第一個文件導出Test ,請執行以下操作:

export default new Test("arg1", "arg2");

從那時起,無論何時導入Test ,您實際上都會獲得在導出語句中創建的相同實例。 只需從之前創建Test對象的任何位置刪除new語句,而只需使用導入的實例。

這是單例設計模式的簡化形式,可以使用 ES6 導入。

暫無
暫無

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

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