簡體   English   中英

Javascript function 返回 object 其中包含 3 個 ZC1C425268E68385D1AB5074C17A94

[英]Javascript function return object which contains 3 function defination but IntelliSense is not working for that return type

I have written a Logger function in javascript and that is a singleton function, from that function I am returning an object that contains the definition of the two functions, So when I am creating an object of that class I get the returned object contains function definition ,並且當我想在該返回值上調用某些內容時,我的代碼 IntelliSense 不起作用,任何人都可以幫助我使用 IntelliSense。 也分享代碼。 我得到了getInstance方法的 IntelliSense,但是當我想使用obj.setDebug時,我沒有得到任何代碼建議或 IntelliSense。

在此處輸入圖像描述

我沒有得到那個 Obj.isDebug 自動完成

const Logger = () => {
  let instance = null
  _isDebug = false

  let setDebug = (value = false) => {
    _isDebug = value
  }

  let isDebug = () => {
    return _isDebug
  }

  createInstance = () => ({
    setDebug,
    isDebug,
    log
  })

  return {
    getInstance: () => {
      if (!instance) {
        instance = createInstance()
      }
      return instance
    }
  }
}

const Log = Logger()
const obj = Log.getInstance();

console.log(obj.setDebug())
console.log(obj.isDebug())

在定義Log時自動執行getInstance ,它會更簡單:

const Logger = () => {
  // Set app
  const app = {
    // Set _isDebug option
    _isDebug: false,
    // Set setDebug method
    setDebug: (value = false) => app._isDebug = value,
    // Get isDebug method
    isDebug: (value = false) => app._isDebug
  };
  
  return app;
}

const Log = Logger();

Log.setDebug(true);
console.log(Log.isDebug());

例子在這里

如果您需要更復雜的 function 和單獨的getInstance方法,只需按照邏輯並隨意添加所需的額外層......下面的代碼只是示例。 在給定的上下文中,正如我之前提到的,這是毫無意義的:

const Logger = () => {
  // Set app
  const app = {
    // Set _isDebug option
    _isDebug: false,
    // Set isDebug method
    setDebug: (value = false) => app._isDebug = value,
    // Get isDebug method
    isDebug: (value = false) => app._isDebug
  };
  
  // Initiator
  const initiator = {
    // Set init status var
    instance: false,
    // Set getInstance method
    getInstance: () => {
      if(!initiator.instance) initiator.instance = app;
      return initiator.instance;
    }
  }
  
  return initiator;
}

const Log = Logger();
const obj = Log.getInstance();

obj.setDebug(true);
console.log(obj.isDebug());

例子在這里

暫無
暫無

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

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