Spedwards
Spedwards

Reputation: 4492

How can I destroy the object created in this constructor?

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.

Upvotes: 0

Views: 103

Answers (2)

dewd
dewd

Reputation: 4429

You have 2 errors in your code.

1)

!Object.prototype.toString.call(header) === '[object Array]'

!Object.prototype.toString.call(header) returns a boolean, so it's never going to equate to [object Array]. This should be:

Object.prototype.toString.call(header) !== '[object Array]'

2)

!typeof(header[i]) == 'string'

the same as above. This should be:

typeof header[i] !== 'string'

The object won't get created if the errors are thrown.

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160261

Your first logic statement isn't doing what you think it is:

if (!Object.prototype.toString.call(header) === '[object Array]') {

The ! is operating on the call results, not the entire expression. Either:

if (!(Object.prototype.toString.call(header) === '[object Array]')) {

or

if (Object.prototype.toString.call(header) !== '[object Array]') {

will work much better. (Same with your second expression.)

Personally I'd lean towards the latter.

(Actually, I'd lean towards encapsulating this check in a separate method or methods, to make it easier to test, and to make the ctor more communicative.)

Upvotes: 0

Related Questions