How to console log the name of a variable/function?

后端 未结 6 1450
梦谈多话
梦谈多话 2020-12-09 12:58

I want to do this: log(variableOrFunction)

And be able to produce this: variableOrFunction: actualValue.

I tried this:



        
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 13:35

    Would this work for you?

    const log = function() {
      const key = Object.keys(this)[0];
      const value = this[key];
      console.log(`${key}:${value}`);
    }
    
    let someValue = 2;
    
    log.call({someVlaue}); //someValue:2
    

    Works with function too, even itself.

    log.call({log});
    
    // It would return the following
    log:function() {
      const key = Object.keys(this)[0];
      const value = this[key];
      console.log(`${key}:${value}`);
    }
    

提交回复
热议问题