如何从新 ES6 class 中的函数插入数据?

How to insert data from functions in new ES6 class?

我可以将数据插入函数的参数吗? 有没有一种方法可以直接 link 存储所有数据的函数的参数,而不是硬编码值?

var data;

function data() {
  this.x = 200,
  this.y = 200,
  this.r = 40,
}

b = new Bubble(data); **//IS THIS CORRECT?**

class Bubble {
  constructor(x, y, r) { 
    this.x = x;
    this.y = y;
    this.r = r;
  }
  move() {
    this.x = this.x + random(-5, 5);
    this.y = this.y + random(-5, 5);
  }
  show() {
    ellipse(this.x, this.y, this.r*2);
  }
}

试试这个

var data;

function data() {
    this.x = 200,
        this.y = 200,
        this.r = 40
}


class Bubble {
    constructor({ 
        x,
        y,
        r
    }) {
        this.x = x;
        this.y = y;
        this.r = r;
    }
    move() {
        this.x = this.x + random(-5, 5);
        this.y = this.y + random(-5, 5);

    }
    show() {
        ellipse(this.x, this.y, this.r * 2);
    }
}
var b = new Bubble(new data());

我正在创建一个数据对象,它类似于 {x:200,y:200,r:40} 会将相同的对象传递给 Bubble 构造函数, 在 Bubble class 构造函数中,它将破坏即将到来的对象并将其分配给 x,y,z.

这是一种非常奇怪的做事方式,但是如果您将构造函数更改为:

class Bubble {
  constructor(initializerFn) { 
    initializerFn.call(this);
  }
}

您传入的函数 datathis 设置为您的新气泡并且它会起作用。

虽然我以前从未见过有人这样做过:)

由于 data 是一个对象,您必须通过在 data 上调用它们来传递 xyz,如下所示:

b = new Bubble(data.x, data.y, data.z);

但是data是一个函数,所以你必须先调用这个函数并得到它的结果,像这样:

var dataObj = new data();
b = new Bubble(dataObj.x, dataObj.y, dataObj.z);

另一件事,当您将 data 传递给不带括号的 Bubble 构造函数时,您传递的是对函数 data 的引用,因此您可以在构造函数中调用它,例如这个:

constructor(dataFn) { 
    var dataObj = dataFn();
    this.x = dataObj.x;
    this.y = dataObj.y;
    this.r = dataObj.r;
}

好的,据我了解。您想要使用 data 函数进行初始化。您可以使用 callapply。因为您需要绑定到 class 的 this

class Bubble {
  constructor(x, y, r) { 
    data.call(this); // it sets this.x, this.y etc
  }
  ....
}

但是我推测,如果您的参数未初始化,您可能希望提供 init 值。所以使用默认参数。

class Bubble {
  constructor(x = 200, y = 200, r = 40) { 
    this.x = x;
    this.y = y;
    this.r = r;
  }
  ...
}

  1. 在你下面的代码中,这个问题的答案正确吗?
var data;

function data() {
  this.x = 200,
  this.y = 200,
  this.r = 40,
}

b = new Bubble(data); **//IS THIS CORRECT?**

没有。您正在创建一个名为 data 的变量,并用一个函数覆盖它。所以你正在传递一个函数。它应该是一个对象。

这里的另一个问题是,变量b的定义没有声明语句(var|const|let),这使得它在非严格模式下是一个全局变量,在严格模式下是错误的。


  1. constructor(x, y, r) {new Bubble(data) 也是错误的。这会将数据分配给 x 并将 yr 设置为默认值 (undefined)

你能做什么:

在构造函数中,您可以使用 Object.assign 来分配作为对象接收的值。您还可以创建一个具有默认值的对象,以确保如果未传递任何值,则将其设置为默认值。

使用Object.assign的另一个好处是,它创建了对象的副本。所以如果对象发生变异,不会对你的对象有任何影响。

样本:

class Bubble {
  constructor(params) {
    const defaultParams = {
      x: 0,
      y: 0,
      r: 0
    }
    Object.assign(this, defaultParams, params)
  }
  move() {
    this.x = this.x + random(-5, 5);
    this.y = this.y + random(-5, 5);
  }
  show() {
    ellipse(this.x, this.y, this.r * 2);
  }
}

const data = { x: 200, y: 200, r: 40 };
const data1 = { x: 150, y: 150, r: 50 };

const b = new Bubble(data);
console.log(b);

const b1 = new Bubble(data1);
console.log(b1);