开发者

Using a string to reference an object name

开发者 https://www.devze.com 2023-01-14 01:33 出处:网络
I\'m trying to replicate a \"feature\" of PHP (And in most languages) in Javascript. Here it is in PHP:

I'm trying to replicate a "feature" of PHP (And in most languages) in Javascript.

Here it is in PHP:

$objectName = 'ObjectA';

$someObject->$objectName->someMethod();

Basically using a string variable to reference an object variable.

So in Javascript, I was hoping to do something like:

var objectName = "ObjectA";

someObject.[objectName].someMethod();
开发者_Python百科

Anyone know how to do this? Or if its even possible?


You almost have it, just remove the first ., like this:

var objectName = "ObjectA";
someObject[objectName].someMethod();

If you want to search for more info around this, it's called bracket notation.

0

精彩评论

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