简体   繁体   English

如何使用括号表示法调用成员函数?

[英]How can I invoke a member function using bracket notation?

var objectliteral = {
    func1:fn(){},
    func2:fn(){},
    .................
    funcn:fn(){}
}

I know I can invoke methods from that object literal using dot notation this: 我知道我可以使用点表示法调用该对象文字中的方法:

objectliteral.func1();

But I would like to do that using array notation like this: 但是我想使用这样的数组符号来做到这一点:

objectliteral[func1]. .... something something......

How do I do that? 我怎么做? I know I can use apply or call methods - but I'm still don't quite get how they work. 我知道我可以使用应用或调用方法 - 但我仍然不太明白它们是如何工作的。

Can I just do this?: 我可以这样做吗?:

objectliteral[func1].apply();

RESOLUTION 解析度

based on answers: 根据答案:

objectliteral['func1']()

is all I need. 我所需要的。 Thanks guys. 多谢你们。

No, do this: 不,这样做:

objectliteral['func1']();

You can also use a dynamic name: 您还可以使用动态名称:

var myfuncname='func1';
objectliteral[myfuncname]();

You can do it like this: 你可以这样做:

var objectLiteral = {
    func1: function() { alert('func1'); },
    func2: function() { alert('func2'); }
};

// This does the same thing...
objectLiteral['func1']();

// As this does
objectLiteral.func1();

你可以试试这个:

objectliteral['func1']();

user objectliteral["funct1"].apply() or objectliteral["funct1"]() . user objectliteral["funct1"].apply()objectliteral["funct1"]()

You can also use a variable to pass the function name 您还可以使用变量来传递函数名称

var funname = "funct1";
objectliteral[funname ]()

你可以做objectliteral["func1"]();

var func1 = 'func1'
objectLiteral[func1]();

Should get you working. 应该让你工作。

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

相关问题 如何在节点 js 中使用括号表示法调用 function - How to call function using bracket notation in node js 如何修复括号vs点表示法Angular.js - How can I fix bracket vs dot notation Angularjs 使用括号表示法在对象内调用函数 - Calling function inside object using bracket notation 使用功能和括号符号将属性添加到对象 - Adding properties to an object using function and bracket notation 仅使用属性访问器(点符号或方括号符号),如何直接设置未定义的嵌套属性? - Using only property accessors (dot notation or bracket notation), how do I set undefined nested properties directly? jsdoc:如何使用括号表示法记录属性? - jsdoc: how to document properties using bracket notation? 为什么我不能使用括号表示法+变量将属性赋值给对象? - Why can't I assign a property to an object using bracket notation + a variable? 如何使用括号符号在对象文字上创建嵌套属性? - How do I create nested properties on object literals using bracket notation? 如何使用括号表示法中的单个变量访问深度值? - how would I go about accessing a deep value using a single variable in bracket notation? 使用 if 和括号表示法理解 reduce 函数 - Understanding a reduce function with if and bracket notation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM