[英]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.