在应用微信小程序的过程中,发现页面向组件中传值或是父子组件中传值并不值传递,本文通过代码试验旨在弄明确值在传递过程中产生的变动。

首先建设一个如下的数据测试类:

export class TestModel {  public _data = 1;  get data() {    console.log('call get data');    if (this._data === 1) {      this._data = Math.random();    }    return this._data;  }}

而后在C层中应用如下测试语句:

    const model = new TestModel();    const model1 = new TestModel();    console.log(model.data);    console.log(model1._data);    this.setData({      testModel:  model    });    console.log(model === this.data.testModel);

最终的运行后果如下:

论断:在调用setData办法时,对象的clone仅限于属性(猜没是用了object 转json而后json又转成了object),办法是不会被clone的。我猜这也是为什么微信小程序在组件传值时,类型仅反对Object但不反对Interface的起因。

而至于为什么会这样,官网是这么解释的:

既然是两个过程,那么在传値时便只能进行序列化与反序列化了,这时是值传递也就难能可贵了。

如果真是这样的话,置信如下的状况会报stack异样:

export class BarModel {  public fooModel: FooModel;}export class FooModel {  public barModel: BarModel;}  onLoad() {    const barModel = new BarModel();    const fooModel =  new FooModel();    barModel.fooModel = fooModel;    fooModel.barModel = barModel;    this.setData({      fooModel: fooModel    });  },

起因则是在序列化时产生了cycle循环。