Issue
I am trying to set prototype of an object using
Object.setPrototypeOf(data,RouteModel.prototype)
at the purpose of use an existing class with methods.
The defined class is the following:
export class RouteModel {
constructor(public absoluteurl:string,public routes:RouteItemModel[]){}
public gettext()
{
return 'asdassdasd'
}
}
and it contains a property routes
as array of RouteItemModel
that contains a method:
export class RouteItemModel {
constructor(
public name: string,
public source_type: string,
public method: string,
public path: string
) {}
public getColorByMethod(): string {
switch (this.method.toLowerCase()) {
case 'get':
return 'success';
case 'put':
return 'warning';
case 'delete':
return 'danger';
default:
return "primary"
}
}
}
On the object.assign the main object go ok and I can use the gettext()
method, but the routes
property doesn't change so I can't use the getColorByMethod()
method.
What's wrong?
Solution
I'd strongly recommend not using setPrototypeOf
if you have any other option, and you almost always do. Instead, just create a RouteModel
and its RouteItemModel
s directly:
const result = new RouteModel(
data.absolute_url,
data.routes.map(({name, source_type, method, path}) => new RouteItemModel(
name,
source_type,
method,
path,
))
)
It would probably be worthwhile to add a from
method to RouteModel
and RouteItemModel
to encapsulate those operations.
If you did have to set setPrototypeOf
...
...but the routes property doesn't change so I can't use the
getColorByMethod()
method.
Just setting the prototype of data
has no effect on those route objects, you'd also have to set the prototype of each route, something like this:
// REALLY DON'T RECOMMEND THIS
Object.setPrototypeOf(data, RouteModel.prototype);
for (const route of data.routes) {
Object.setPrototypeOf(route, RouteItemModel.prototype);
}
Again, though, resetting the prototype of existing objects is (almost?) never necessary and its confusing to people reading the code. (It used to impact the subsequent performance of those objects as well, although that rarely mattered; I haven't checked lately to see if that's still true, since I never do this.)
Answered By - T.J. Crowder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.