繁体   English   中英

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

[英]How to insert data from functions in new ES6 class?

如何将数据插入函数的参数中? 不用硬编码的值,还有一种方法可以直接将参数链接到存储所有数据的函数?

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类的构造函数中,它将破坏即将到来的对象并分配到x,y,z。

这是一种很奇怪的处理方式,但是如果您将构造函数更改为:

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

您传入的函数data会将this设置为您的新气泡,它将起作用。

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

由于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 因为你需要绑定到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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM