I am declaring a class Response with multiple instance method of this class like the code below but I am getting an error throwing from the output: Error: Cannot read properties of undefined (reading 'payload')
. I want to get results from what I am calling to get. How can I do it?
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 }
CodePudding user response:
From what I can understand, you are trying to make chainable methods (similar to what the String class does.)
To make chainable methods, you have almost done the right thing, except in the output
method, you return a plain object. This isn't right because then it just returns an object and not an instance of the Response
class.
So, the output
method should return something like:
output({
message = null,
payload = null,
data = null
}) {
return new Response({
message,
payload,
data
})
}
Additionally, you should also have a constructor that accepts the required parameters and stores them in a global object (like a state variable).
That would make your class look like:
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
})
}
}
Additionally, to make it even more efficient, you can replace the new Response()
call in the output
function to be:
output({
message = null,
payload = null,
data = null
}) {
this.state = {
message,
payload,
data
}
return this // this returns an instance of the class
}
This covers your back if you should change the class name in the future, you need not come back to the output
function and change the return new Response()
to return new NewClass()
everytime.
Hope it helped!