简体   繁体   中英

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, and when I want to call something on that returned value my code IntelliSense is not working, can anybody help me with the IntelliSense. Also sharing the code. I am getting the IntelliSense for the getInstance method, but when i wan to use obj.setDebug I am not getting any code suggestion or IntelliSense for that part.

在此处输入图像描述

That Obj.isDebug autocomplete i am not getting

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())

Do getInstance automatically while defining Log , it'll be more simple:

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

Example is here

If you need more complex function with separate getInstance method, just follow the logic and feel free to add as much additional layers as you need... Below code is just for example. In given context it is pointless as I've mentioned before:

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

Example is here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM