简体   繁体   English

使用括号表示法在对象内调用函数

[英]Calling function inside object using bracket notation

If i have a function defined inside some object as in : 如果我在某个对象中定义了一个函数,如:

var myobject={
myfunction:function(){//mycode here}
}

usually you can access the function using: 通常您可以使用以下方法访问该功能

myobject.myfunction()

but what if i want to use 但如果我想使用该怎么办?

myobject["myfunction"]

trying so , actually the function did not get called , how can i call the function using brackets notation ? 尝试这样,实际上函数没有被调用,我怎么能用括号表示法调用函数?

Use it like. 像它一样使用它。 You were very close 你非常接近

myobject["myfunction"]();

You can also do this 你也可以这样做

var myfuncname="myfunction";
myobject[myfuncname]();

The two forms 这两种形式

myobject.myfunction;

and

myobject["myfunction"];

are equivalent as long as you only use a fixed string to access the member (using a computed value is a different matter, then you must use the second form). 只要您只使用固定字符串来访问该成员(使用计算值是另一回事,那么您必须使用第二种形式)是等效的。 Both lines result in the function-object-member myfunction which you can assign to a variable if you like, and calling that: 这两行都会产生function-object-member myfunction ,如果你愿意,你可以将它分配给一个变量,然后调用:

var myfunc = myobject.myfunction;
myfunc();

Note that assigning it to the variable breaks the this variable, so you might not want to do that if you're doing OOP. 请注意,将其分配给变量会破坏this变量,因此如果您正在执行OOP,则可能不希望这样做。

And as you noted, calling a function means adding () with an argument list afterwards, it doesn't matter that the function is acquired through an expression, so either: 正如您所指出的,调用函数意味着在事后列表中添加() ,通过表达式获取函数并不重要,因此:

myobject.myfunction();

or 要么

myobject["myfunction"]();

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

相关问题 使用功能和括号符号将属性添加到对象 - Adding properties to an object using function and bracket notation 实现一个函数来访问对象的属性,而不是使用点符号或方括号符号来访问属性? - Implementing a function to access an object's property versus accessing the property using dot notation, or bracket notation? 使用括号符号访问对象中的属性 - Accessing Properties in object using bracket notation javascript中使用方括号表示法的嵌套对象 - Nested object using square bracket notation in javascript 在angular中,如何通过模板内的括号表示法访问对象属性? - In angular, how to access object property via bracket notation inside templates? 使用对 object 没有影响的括号表示法迭代保存到 object - Iteratively saving to an object using bracket notation having no effect on object 使用Lodash`_.get`使用括号表示法访问对象键 - Using Lodash `_.get` to access object key using bracket notation 无法使用“ .nested”标志和括号表示法检查嵌套对象的属性 - Unable to check a nested object property by using the “.nested” flag and bracket notation 使用括号符号(带有变量)访问对象属性的好处 - Benefit of using bracket notation (with variables) to access a property of an object 使用javascript方括号表示法重新排列对象中的值 - Using javascript square bracket notation to re-arrange values in object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM