简体   繁体   English

从内部函数获取对象键名称?

[英]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? 无论如何有没有打印出“测试”这个函数是值的键,但事先不知道obj名称?

Not really. 并不是的。 Relationships in JS are one-way. JS中的关系是单向的。

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. 使用bind方法,我们可以将函数的第一个参数预定义为用于添加它的键。 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. 我要添加到键的函数是_template ,它的第一个参数始终是它添加到的键。

 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() 参考-Function.prototype.bind()

try this Object.keys(this) and arguments.callee 试试这个Object.keys(this)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 您可以获取使用arguments.callee.name调用的方法的名称

 var a ={ runner_function : function(){ console.log(arguments.callee.name ); } }; a.runner_function() //It will return "runner_function" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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