From example code below I'm trying to add a method inside an object where it generates new name based on object properties but "this" in this context is referring global object but not the parent one
It's ok using arrow function but the functions won't be hoisted and I need to express the function before using it. I prefer knowing what it does before seeing the code.
using arrow function expression it does work but is not hoisted using function declaration it doesn't work but is hoisted
Is there any best practice approach to this kind of problem?
const agent = {
firsName: "John",
lastName: "Depp",
born: 12/04/1987,
secretName: function() {
return newFirstName() + newLastName()
function newFirstName() {
// complex codes here
return "Agent " + this.firstName // for simplicity
}
function newLastName() {
// complex codes here
return "Agent " + this.LastName // for simplicity
}
},
};
console.log(agent.secretName()) // logs "Agent undefinedAgent undefined"