mercredi 6 mai 2015

JavaScript Class Validation

So I'm making a JavaScript class that will be transferable with my Java one. It's all done but I want to make sure the right data type gets entered for the arguments.

For example, my Constructor:

function Table(header) {
    if (!Object.prototype.toString.call(header) === '[object Array]') {
        throw 'headers not array';
        return;
    }
    for (var i = 0; i < header.length; i++) {
        if (!typeof(header[i]) == 'string') {
            throw 'headers['+i+'] not string';
            return;
        }
    }
    this.header = header;
    this.rows = [];
}

When you create a new Table object, you have to pass in an array. Though you can pass in anything here and the object still gets created, just without the header and rows fields.

How can I destroy the object? The errors I've tried to throw don't do anything.

Aucun commentaire :

Enregistrer un commentaire