[英]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
上调用x
, y
和z
来传递它们,如下所示:
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
功能初始化。 您可以使用call
或apply
。 因为你需要绑定到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; } ... }
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
),这使其在非严格模式下成为全局变量,而在严格模式下出错。
constructor(x, y, r) {
和new Bubble(data)
也是错误的。 这将为x
分配数据,并将y
和r
设置为默认值( 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.