Skip to content Skip to sidebar Skip to footer

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 arra

Solution 1:

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:

functioncreateNode(str, isTextNode)
{
    returndocument[isTextNode ? "createTextNode" : "createElement"](str);
}

Post a Comment for "Javascript Accessing Methods With Brackets?"