从构造函数初始化Typescript类值 [英] Initializing Typescript class values from constructor

查看:435
本文介绍了从构造函数初始化Typescript类值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用TypeScript通过KnockoutJS创建一些类,数据从WebAPI返回的一些JSON加载。

I'm using TypeScript to create some classes with KnockoutJS, with the data being loaded from some JSON returned by WebAPI.

问题是我想复制JSON值从构造函数中插入到我的TypeScript类中:但是如果我只在基类上这样做,那么继承的属性没有被定义,所以不会初始化。

The problem is I wanted to copy the JSON values into my TypeScript class from the constructor: but if I do this just at the base class, the inherited properties have not been defined and so are not initialised.

示例

我们要从JSON回应建立库存项目:

We want to create an inventory item from a JSON response:

{ Name: "Test", Quantity:1, Price: 100 }

产品和继承类库存:

export class Product {
  Name = ko.observable("");

  constructor(source) {
    // a utility that copies properties into this instance
    utils.CopyProperties(source,this);
  }

export class Inventory extends Product {
  Quantity = ko.observable(0);
  Price = ko.observable(0);

  constructor(source) {
    super(source); // call base c'tor
    // the quantity and price properties are only now defined
  }
}

Inventory的属性仅在 super 构造函数调用后的JS输出代码中创建,因此在执行Product构造函数时不存在。

The properties for Inventory are only created in the JS output code after the super constructor call, so do not exist when the Product constructor is executed.

我可以看到的唯一解决方案是从构造函数中取出初始值,但我不喜欢这种方法,虽然我怀疑这是唯一的选择。 >

The only solution I can see is to take the initialising value out of the constructor, but I don't really like this approach, although I suspect it's the only option.

  var inventoryItem = new Inventory();
  inventoryItem.LoadFrom(source);


推荐答案

从构造函数调用的基本反序列化例程是这个(修改为删除测试的敲除依赖):

Best I can come up with to allow you to have a base deserialization routine that is called from the constructor is this (modified to remove knockout dependency for testing):

class utils {
    public static CopyProperties(source:any, target:any):void {
        for(var prop in source){
            if(target[prop] !== undefined){
                target[prop] = source[prop];
            }
            else {
                console.error("Cannot set undefined property: " + prop);
            }
        }
    }
}

class Product {
  Name = "Name";

  constructor(source) {
    this.init(source);
  }

  init(source){
     utils.CopyProperties(source,this);
  }
}

class Inventory extends Product {
  Quantity;
  Price;

  constructor(source) {
    super(source);
  }

  init(source){
      this.Quantity = 0;
      this.Price = 0;
      super.init(source);
  }
}

var item = new Inventory({ Name: "Test", Quantity: 1, Price: 100 });

这是奇怪的是,变量只在JS调用 super()。也许值得在codeplex上提出工作项

游乐场

这篇关于从构造函数初始化Typescript类值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆