简体   繁体   English

使用变量作为函数名称可能会涉及多个层次

[英]Using a variable as a function name that could be multiple levels deep

I have had a look around the site and seem to have come across some solutions, but none seem to work. 我浏览了该站点,似乎遇到了一些解决方案,但似乎没有一个可行。 So here's the problem. 这就是问题所在。

I have the following Javascript: 我有以下Javascript:

 THEOBJECT = { init: function() { this.tools.init(); } }; THEOBJECT.tools = { active: false, init: function() { // active variable updated elsewhere/loading if (!this.active) { THEOBJECT.utils.timeout('tools.init', 100); } // is active so continue } }; THEOBJECT.utils = { timeout: function(functionName, time) { setTimeout(function() { THEOBJECT[functionName](); }, time); } }; THEOBJECT.init(); 

I am getting an error when running the THEOBJECT.utils.timeout saying: 运行THEOBJECT.utils.timeout时出现错误:

THEOBJECT[functionName] is not a function THEOBJECT [functionName]不是函数

I'm trying to run THEOBJECT.tools.init() 我正在尝试运行THEOBJECT.tools.init()

I'm assuming this is because it's not a direct function of the THEOBJECT object is there a way around this or is a split() the best way to go? 我假设这是因为它不是THEOBJECT对象的直接函数,是否可以解决这个问题,或者split()是最好的方法吗?

There is other option to do it using lodash.js . 使用lodash.js还有其他选择。 Please see the updated snippet. 请查看更新的代码段。

Or go with conventional approch mentioned below 或采用下面提到的常规方法

You are trying to access a property in wrong way 您正在尝试以错误的方式访问属性

you are doing THEOBJECT[tools.init] which incorrect. 您正在执行不正确的THEOBJECT[tools.init] It should be like THEOBEJECT[tools][init] 它应该像THEOBEJECT[tools][init]

 THEOBJECT = { init: function() { this.tools.init(); } }; THEOBJECT.tools = { active: false, init: function() { // active variable updated elsewhere/loading if (!this.active) { THEOBJECT.utils.timeout('tools.init', 100); } console.log("active") // is active so continue } }; THEOBJECT.utils = { timeout: function(functionName, time) { setTimeout(function() { _.get(THEOBJECT,functionName); }, time); } }; THEOBJECT.init(); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script> 

you can also go with a simple reduce and make it a one-liner: 您还可以使用简单的reduce使其成为单线:

functionName.split('.').reduce((acc,curr) => return acc[curr], THEOBJECT)();

within your code: 在您的代码中:

 THEOBJECT = { init: function() { this.tools.init(); } }; THEOBJECT.tools = { active: false, init: function() { // active variable updated elsewhere/loading if (!this.active) { THEOBJECT.utils.timeout('tools.init', 100); } // is active so continue } }; THEOBJECT.utils = { timeout: function(functionName, time) { setTimeout(function() { functionName.split('.').reduce((acc,curr) => acc[curr],THEOBJECT)(); }, time); } }; THEOBJECT.init(); 

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

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