[英]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.