1

I have class to which I set property values in a for loop. One of the properties is object, class respectively.

But after the for loop ends, this property loses its type and it is cast to simple Object. Why?

public setAttributes(data:any):void {
   for (var name in data) {
       if (this.hasOwnProperty(name)) {
            switch (name) {
                case 'restaurant':
                    this.restaurant = new Restaurant(data.restaurant);
                    console.log(this.restaurant); //log 1
                default:
                    this[name] = data[name];
            }
        }
    }
    console.log(this.restaurant); //log 2
    this.restaurant = new Restaurant(data['restaurant']);
    console.log(this.restaurant); //log 3
}

Calling function with

this.setAttributes({
    title: 'test',
    restaurant: {
        title: 'restaurant test'
    }
})

results in

Restaurant {title: 'restaurant test'} //log 1
Object {title: 'restaurant test'} //log 2
Restaurant {title: 'restaurant test'} //log 3

Why the second log (//log 2) has type Object but not Restaurant?

Thanks for your replies.

1 Answer 1

4

You need a break statement here to avoid overwriting this.restaurant right after you initialize it:

public setAttributes(data:any):void {
   for (var name in data) {
       if (this.hasOwnProperty(name)) {
            switch (name) {
                case 'restaurant':
                    this.restaurant = new Restaurant(data.restaurant);
                    console.log(this.restaurant); //log 1
                    break; // oops! was falling through
                default:
                    this[name] = data[name];
            }
        }
    }
    console.log(this.restaurant); //log 2
    this.restaurant = new Restaurant(data['restaurant']);
    console.log(this.restaurant); //log 3
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you :) I was wondering about some JS behaviour I do not know. And look at that, what a silly mistake

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.