Is there any way to invoke a method on each property instead of calling it on the obj and giving property as argument?
For example if I have an object like this:
const obj = { person: "John Smith" };
I know I can add a method like the following to the object:
addM(p) { return "Mr. " + p; }
and then call it as:
obj.addM(obj.person)
But is there any way to define the method that can be invoked like:
obj.person.addM()
or even better: obj.person.addM
Sorry if I simplified the question too much, I believe I can figure out how to code what I want in my project if I know the solution of this simple problem.
Actually I have some nested objects so please consider it in answering if necessary.
For example if I have:
const obj = {
person1: { firstName: "John", lastName: "Smith" },
person2: ...,
.
fullName() {
return this.firstName + this.lastName;
}
};
I want to invoke it as obj.person1.fullName
2
Answers
put full name function in your object
to call new Name
You can use Object.defineProperty, As the MDN explain: "The Object.defineProperty() static method defines a new property directly on an object, or modifies an existing property on an object, and returns the object."
In this example, use
Object.defineProperty
for every obj child add a new propertyfullName