在赋值后,对象实例将转换为Object

时间:2017-03-10 18:11:50

标签: javascript typescript

我有一个类,我在for循环中设置了属性值。其中一个属性分别是object,class。

但是在for循环结束后,此属性将丢失其类型,并将其强制转换为简单Object。为什么呢?

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
}

使用

调用功能
this.setAttributes({
    title: 'test',
    restaurant: {
        title: 'restaurant test'
    }
})

结果

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

为什么第二个日志( // log 2 )的类型为对象,而不是餐馆

感谢您的回复。

1 个答案:

答案 0 :(得分:4)

此处需要break语句,以避免在初始化后立即覆盖this.restaurant

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
}