简体   繁体   中英

Square brackets after object creation

I have a problem with the following code:

// At the beginning
var prog = {}
// some attributes of prog and other methods
// ...

prog.stateChange = function(state)
{
    var functionOfState =
    {
        onState1: function()
        {
           // some code
        },

        onState2: function()
        {
            // some code
        } 
    }['on'+state]()
}

Which purpose have these square brackets after the creation of the object functionOfState? Is this an array of possible methods?

Sorry, I'm a total newbie in JS and I haven't found any information about this. I really appreciate any help.

This code does almost the same as:

var functionOfState =
{
    onState1: function()
    {
       // some code
    },

    onState2: function()
    {
        // some code
    } 
}

functionOfState['on'+state]();

It simply creates an object which stores different functions. Then, it calls one of them according to the current value of state .

Maybe, this one will be even easier:

var functionOfState = {};

functionOfState['onState1'] = function() { 
    // someCode
};

functionOfState['onState2'] = function() { 
    // someCode
};

functionOfState['on'+state](); // when state is 'State2', 'onState2' will be called

The difference that in your code it doesn't store this object with functions, but calls it directly.

This is (not the most clear) way to extract field from an object.
in JS, the subscript operator ( [] ) can extract a property out of an object just like the dot operator ( . ), so the following expressions are equal:

var obj = { field : value };
obj.field == obj["field"]; //returns true

on your example an object with the fields onState1 , onState2 is created. then, using the subscript operator the correct property is extract. it is equivilant on writing

prog.stateChange = function(state)
{

    var temp = 
    {
        onState1: function()
        {
           // some code
        },

        onState2: function()
        {
            // some code
        } 
    };
  var functionOfState = state == onState1 ? temp.onState1 : temp.onState2;
  functionOfState();
}

This is not a legit way to extract a property/method out of an object. basically if someone changes the name of the method, the code breaks. it is much better to simply use a switch case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM