Javascript accessing methods with brackets?
I saw this in some code:
var _0xdf50x7 = document['createElement']('form');
How does this work? Does this mean that an object's methods can be accessed like the elements of an开发者_开发知识库 array?
Since the createElement()
method is a member of the document
object, it can be accessed using either dot notation:
var form = document.createElement("form");
Or bracket notation:
var form = document["createElement"]("form");
This can be useful if the name of the method to call is stored in a variable:
var methodName = "createElement";
var form = document[methodName]("form");
It can also be used if the actual method to call depends on external conditions. Here is a (contrived) example:
function createNode(str, isTextNode)
{
return document[isTextNode ? "createTextNode" : "createElement"](str);
}
精彩评论