简体   繁体   中英

Getting Object Key Name from inside function?

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?

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.

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

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

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" 

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