Assuming I have the following object:
let obj={
childone: (value) => {
return value+1;
},
childtwo: (value) => {
return value+3;
},
childsingle: (value) => {
return value+1;
}
};
Is there any method to set obj.childsingle
equal to obj.childone
within the same declaration?
I'm trying to achieve childsingle=childone
within the object declaration.
I also tried to use get
as per duplicated suggested answers.
However, after using this:
let obj = {
childone: (value) => {
return value+1;
},
childtwo: (value) => {
return value+3;
},
get childsingle() {
return this.childone;
}
};
I get handleError TypeError: childsingle is not a function
.
The Object. assign() method can be used to merge two objects and copy the result to a new target. Just like the spread operator, If the source objects have the same property name, the latter object will replace the preceding object. Now, let's look at another example of merging in Typescript.
To use the Object. assign() method in TypeScript, pass a target object as the first parameter to the method and one or more source objects, e.g. const result = Object. assign({}, obj1, obj2) . The method will copy the properties from the source objects to the target object.
You can use getter
method for childsingle
declaration. Example is shown below.
Here in it will always return childone
when you call for childsingle
even if you update childone
childone
will always point to latest childone
.
For more information refer Defining getters and setters Section
let obj = {
childone: (value) => {
return value+1;
},
childtwo: (value) => {
return value+3;
},
get childsingle() {
return this.childone;
}
};
console.log(obj.childsingle(10));
What is the reason to avoid:
let obj = {
childone: (value) => {
return value + 1;
},
childtwo: (value) => {
return value + 3;
},
childsingle: (value) => {
return obj.childone(value);
}
};
It provides:
console.log(obj.childone(1)); // 2
console.log(obj.childsingle(2)); // 3
Lexical scoping keeps in honest in more advanced scenarios too:
function getObj() {
const obj = {
childone: (value) => {
return value + 1;
},
childtwo: (value) => {
return value + 3;
},
childsingle: (value) => {
return obj.childone(value);
}
};
return obj;
}
const example = getObj();
console.log(example.childone(1));
console.log(example.childsingle(2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With