2

Say I have an object like below:

var obj = {};
obj.test = function() { console.log(?); }

Is there anyway to print out "test", the key that this function is value of, but not know the obj name in advance?

Noobit
  • 411
  • 3
  • 8
  • Why do you want to do this? A function is just a value. It has no idea what object(s) it may or may not be a member of. It could be the value of multiple properties on an object. –  May 05 '17 at 05:10

4 Answers4

0

Not really. Relationships in JS are one-way.

You could search for a match…

var obj = {};
obj.not = 1;
obj.test = function() {
  var me = arguments.callee;
  Object.keys(obj).forEach(function(prop) {
    if (obj[prop] === me) {
      console.log(prop);
    }
  });
};

obj.test();

But look at this:

var obj = {};
obj.not = 1;
obj.test = function() {
  var me = arguments.callee;
  Object.keys(obj).forEach(function(prop) {
    if (obj[prop] === me) {
      console.log(prop);
    }
  });
};
obj.test2 = obj.test;
obj.test3 = obj.test;
window.foo = obj.test;

obj.test();

The same function now exists on three different properties of the same object … and as a global.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Might be a bit of a convoluted solution, but this might be useful -

You can have a method that will add functions to your object at a specific key. Using the bind method, we can predefine the first argument to the function to be the key that was used to add it. The function that I am adding to the key is _template, it's first argument will always be the key that it was added to.

var obj = {};
    
function addKey(key) {
  obj[key] = _template.bind(null, key)
}
    
function _template(key, _params) {
  console.log('Key is', key);
  console.log('Params are',_params);
}


addKey('foo')
obj.foo({ some: 'data' }) // this will print "foo { some: 'data' }"

Reference - Function.prototype.bind()

Lix
  • 47,311
  • 12
  • 103
  • 131
-1

try this Object.keys(this) and arguments.callee

var obj = {};
obj.test = function() {
  var o = arguments.callee;
 Object.values(this).map((a,b)=>{
   if(a==o){
   console.log(Object.keys(this)[b])
   }
  })
}
obj.one = "hi"

obj.test()
prasanth
  • 22,145
  • 4
  • 29
  • 53
-1

You can get the name of the method called with arguments.callee.name

var a ={ runner_function : function(){ console.log(arguments.callee.name ); } };

a.runner_function() //It will return "runner_function"
jmtalarn
  • 1,513
  • 1
  • 13
  • 16
  • You probably want to add a disclaimer that `arguments.callee` is deprecated - http://stackoverflow.com/questions/103598/why-was-the-arguments-callee-caller-property-deprecated-in-javascript/235760#235760 – Lix May 04 '17 at 14:47
  • This doesn't seem to work for keys that added after object is initialized like in my example. it returns as "" (blank) – Noobit May 04 '17 at 14:55