How to structure the parameters in a javascript object

Asked

Viewed 31 times

0

I have the following code:

 var colHeaders = [
    "Column 1",
    "Column 2"
];

var columns = [
    {data: 'column_1', validator: validatorRentalCode, allowEmpty: false, allowInvalid: false},
    {data: 'column_2', type: 'numeric', numericFormat: typeNumber, allowEmpty: false},
];

var options = {
    columns: columns,
    colHeaders: colHeaders
};
div = document.querySelector('#table');
var table = new Table(div, options);

As variables are part of the context of the Table Object. I would like to improve and transform the variables into parameters as below:

var Table = {
    TABLE: {
        HEADERS: [
            "Column 1",
            "Column 2"
        ],
        COLUMNS: [
            {data: 'horas_extras', type: 'time', timeFormat: 'hh:mm', correctFormat: true, allowEmpty: false}
        ]
    },
    OPTIONS: {
        columns: this.TABLE.COLUMNS,
        colHeaders: this.TABLE.HEADERS
    }
};

In this my change there ended up occurring a undefined: Cannot read property 'COLUMNS' of undefined. Because I have a basic knowledge of language, I believe the property COLUMNS does not exist at the time of the creation of the object.

What would be the best way to solve this problem of mine?

1 answer

1

In fact what is giving Undefined would be your this.TABLE because when running this inside your object it is picking up the scope from outside, and not from the object.

A valid course of action would be:

var gerarTable = function () {

    var columns = [{data: 'horas_extras', type: 'time', timeFormat: 'hh:mm', correctFormat: true, allowEmpty: false}];
    var headers = ["Column 1","Column 2"];

    return {
        TABLE: {
            HEADERS: headers,
            COLUMNS: columns
        },
        OPTIONS: {
            columns: columns,
            colHeaders: headers
        }
    };
};

and when executing it returns you to Table:

var Table = gerarTable();

A tip of mine is to open the browser console (F12) and start playing on the console with the javascript codes, it has access to the javascript page.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.