开发者

Javascript accessing methods with brackets?

开发者 https://www.devze.com 2023-03-28 07:00 出处:网络
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开发者_开发知识库

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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消