Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript accessing methods with brackets?

Tags:

javascript

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?

like image 963
mowwwalker Avatar asked Feb 03 '26 09:02

mowwwalker


1 Answers

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);
}
like image 191
Frédéric Hamidi Avatar answered Feb 05 '26 23:02

Frédéric Hamidi