![](/img/trans.png)
[英]How to use the same javascript function on multiple HTML divs with the same class
[英]how to call multiple function of same class in JavaScript?
我正在使用此類的多個實例方法聲明一個類 Response,如下面的代碼,但我從輸出中拋出錯誤: Error: Cannot read properties of undefined (reading 'payload')
。 我想從我打電話得到的結果中得到結果。 我該怎么做?
class Response { output({ message = null, payload = null, data = null }) { return { message, payload, data } } message(message) { this.output({ message }) } payload(payload) { this.output({ payload }) } data(data) { this.output({ data }) } } const response = new Response(); console.log( response.message('my message').payload('my payload').data('my data') ); // expected result: { message: 'my message', payload: 'my payload', data: 'my data' } console.log( response.message('my message').payload('my payload') ); // expected result: { message: 'my message', payload: 'my payload', data: null } console.log( response.payload('my payload') ); // expected result: { message: null, payload: 'my payload', data: null }
據我所知,您正在嘗試制作可鏈接的方法(類似於 String 類所做的。)
要制作可鏈接的方法,您幾乎做對了,除了在output
方法中,您返回一個普通對象。 這是不對的,因為它只返回一個對象而不是Response
類的實例。
因此, output
方法應該返回如下內容:
output({
message = null,
payload = null,
data = null
}) {
return new Response({
message,
payload,
data
})
}
此外,您還應該有一個接受所需參數並將它們存儲在全局對象(如狀態變量)中的構造函數。
那會讓你的班級看起來像:
class Response {
state = {
message: null,
payload: null,
data: null
}
constructor(params) {
// be careful, params can also be null when calling the constructor with no arguments.
// handle it accordingly
this.state = params
}
output({
message = null,
payload = null,
data = null
}) {
return new Response({
message,
payload,
data
})
}
message(message) {
this.output({
message
})
}
payload(payload) {
this.output({
payload
})
}
data(data) {
this.output({
data
})
}
}
此外,為了使其更加高效,您可以將output
函數中的new Response()
調用替換為:
output({
message = null,
payload = null,
data = null
}) {
this.state = {
message,
payload,
data
}
return this // this returns an instance of the class
}
如果您將來要更改類名,這將覆蓋您的背部,您無需返回output
函數並將return new Response()
更改為return new NewClass()
每次。
希望它有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.